一个查询弹性搜索中的多个子查询

时间:2017-06-29 15:52:36

标签: elasticsearch lucene bigdata

我的索引名为字典,其中包含关键字,映射关键字和类别过滤器等字段。

Keyword   Mapped Keyowrd       Category
-------   --------------       --------
apple     apple iphone         smartphones
apple     apple watch          smart watches
apple     apple ipad           tablets

因此,如果用户搜索apple,则内部查询将搜索具有相应类别的映射关键字,如下面的查询。

SELECT * FROM products where (title= "*apple*" AND title="*iphone*" and category="smartphones") OR (title= "*apple*" AND title="*ipad*" and category="tablets") OR (title= "*apple*" AND title="*watch*" and category="smart watches")

下面是我写过的相应的弹性搜索查询。

{
   "query": {
      "bool": {
         "should": [
            {
               "bool": {
                  "must": [
                     {
                         "match" : {
                            "title" : {
                                "query" : "apple iphone",
                                "operator" : "and"
                            }
                        }
                     },
                     {
                        "term": {
                           "category.raw": "smartphones"
                        }
                     }
                  ]
               }
            },
            {
               "bool": {
                  "must": [
                     {
                        "match" : {
                            "title" : {
                                "query" : "apple watch",
                                "operator" : "and"
                            }
                        }
                     },
                     {
                        "term": {
                           "category.raw": "smartwatch"
                        }
                     }
                  ]
               }
            },
            {
               "bool": {
                  "must": [
                     {
                       "match" : {
                            "title" : {
                                "query" : "apple ipad",
                                "operator" : "and"
                            }
                        }
                     },
                     {
                        "term": {
                           "category.raw": "tablets"
                        }
                     }
                  ]
               }
            }
         ],
         "minimum_should_match": 1
      }
   }
}
  • 以上查询是否正确?上述查询中需要进行哪些更改?
  • 有没有办法通过在此查询中添加一些参数来获取elasticsearch中每个子查询的前10个结果?

1 个答案:

答案 0 :(得分:0)

是的,就我所知,你的查询看起来很好。 "minimum_should_match": 1并非真正必要,这是默认行为。

您可以使用function_score查询(可能使用script_score)来强加这种逻辑,但我认为更好的方法是执行三个不同的查询,并获得每个结果。如果要在一个请求中执行这些多个查询,可以使用Multi Search API

执行此操作
相关问题