Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elasticsearch: "More like this" combined with additional constraint

I just bumped into "more like this" functionality/api. Is there a possibility to combine the result from more_like_this with some additional search constraint?

I have two following ES query which works:

POST /h/B/_search
{
   "query": {
      "more_like_this": {
         "fields": [
            "desc"
         ],
         "ids": [
            "511111260"
         ],
         "min_term_freq": 1,
         "max_query_terms": 25
      }
   }
}

Which returns

{
   "took": 16,
   "timed_out": false,
   "_shards": {
      "total": 3,
      "successful": 3,
      "failed": 0
   },
   "hits": {
      "total": 53,
      "max_score": 3.2860293,
      "hits": [
      ...

Which is fine but I need to specify additional constraint over other field of the underlying document which works separately fine:

POST /h/B/_search
{
   "query": {
      "bool": {
         "must": {
            "match": {
               "Kind": "Pen"
            }
         }
      }
   }
}

I would love to combine those two to one, as the query should state: "Find a similar items to items labelled with Pen". I tried following with nested query but that gives me some error back:

POST /h/B/_search
{
   "query": {
      "more_like_this": {
         "fields": [
            "desc"
         ],
         "ids": [
            "511111260"
         ],
         "min_term_freq": 1,
         "max_query_terms": 25
      },
      "nested": {
         "query": {
            "bool": {
               "must": {
                  "match": {
                     "Kind": "Pen"
                  }
               }
            }
         }
      }
   }
}

I tried several variant for combining those two search criteria but so far with no luck. If someone more experienced could provide some hint that would be really appreciated.

Thanks

like image 995
jaksky Avatar asked Mar 23 '15 17:03

jaksky


1 Answers

bool queries are used exactly for this purpose. A bool must is basically equivalent to the Boolean AND operation. Similarly you can use bool should for Boolean OR and bool must_not for Boolean NOT operations.

POST /h/B/_search
{
   "query": {
      "bool": {
         "must": [
            {
               "more_like_this": {
                  "fields": [
                     "desc"
                  ],
                  "ids": [
                     "511111260"
                  ],
                  "min_term_freq": 1,
                  "max_query_terms": 25
               }
            },
            {
               "match": {
                  "Kind": "Pen"
               }
            }
         ]
      }
   }
}
like image 55
bittusarkar Avatar answered Sep 21 '22 16:09

bittusarkar