elasticsearch:“更像这样”加上额外的约束

时间:2015-03-23 17:06:01

标签: elasticsearch

我刚刚碰到“更像这样”的功能/ api。是否有可能将more_like_this的结果与一些额外的搜索约束结合起来?

我有两个跟随ES查询的工作:

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

返回

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

哪个好,但是我需要在底层文档的其他字段中指定附加约束,它可以单独运行:

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

我希望将这两者结合起来,因为查询应该说明:“查找与标有Pen的项目类似的项目”。我尝试使用嵌套查询,但这给了我一些错误:

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"
                  }
               }
            }
         }
      }
   }
}

我尝试了几种变体来结合这两个搜索条件,但到目前为止没有运气。 如果有经验的人可以提供一些非常感激的提示。

由于

1 个答案:

答案 0 :(得分:7)

bool queries完全用于此目的。 bool must基本上等同于Boolean AND操作。同样,您可以bool should使用Boolean OR进行bool must_not Boolean NOT {/ 1}}。

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"
               }
            }
         ]
      }
   }
}