Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add filter to a more like this query in Elastic Search?

I want to use a More like this query in Elastic Search to find similar documents. However I need to filter the documents on which the query is executed.

Example below: I want to find blog items that are similar to blog with id 123456, but written by author 120 or author 123.

When executing this query, I get back similar blogs from ALL authors and thus not filtered ...

{
  "query":{
    "more_like_this" : {

        "fields" : ["body" ],  
        "docs" : [
              {
                "_id" : "123456"
              }
            ],
        "percent_terms_to_match" : 0.4,
            "min_term_freq" : 1
      }
  }
 },

"filter":{
  "and":[            
          {
            "type":{ "value":"blog" }
          },
          {
            "terms":{ "authorId": ["120", "123"] }
          }
        ]
}
}
like image 873
cyclomarc Avatar asked May 30 '14 18:05

cyclomarc


People also ask

What is the difference between query and filter in Elasticsearch?

Queries are slower it returns a calculated score of how well a document matches the query. Filters are faster because they check only if the document matched or not. Queries produce non-boolean values. Filters produce boolean values.

In which order are my Elasticsearch queries filters executed?

Q: Do filters get executed before or after queries? A: Neither, really. Everything is interleaved, regardless of whether they are queries of filters.


1 Answers

Try filtered query like this:

{
    "query": {
        "filtered": {
            "query": {
                "more_like_this": {
                    "fields": [
                        "body"
                    ],
                    "docs": [
                        {
                            "_id": "123456"
                        }
                    ],
                    "percent_terms_to_match": 0.4,
                    "min_term_freq": 1
                }
            },
            "filter": {
                "and": [
                    {
                        "type": {
                            "value": "blog"
                        }
                    },
                    {
                        "terms": {
                            "authorId": [
                                "120",
                                "123"
                            ]
                        }
                    }
                ]
            }
        }
    }
}

Hope it helps...!

like image 109
BlackPOP Avatar answered Nov 07 '22 19:11

BlackPOP