使用AND运算符在弹性搜索中搜索

时间:2016-12-13 07:42:30

标签: elasticsearch

我的ES中有以下文件

  name                 type
Thomas Robert King     xyz
Peter  Jacob  Junior   xyz
Robert Einstein Jr     abc
Thomas Jupyin   DR     xyz

我希望得到所有与Robert和Thomas匹配的文档,并且都是xyz类型。

我创建的当前ES查询是:

http://localhost/index/type/_search/?size=100&pretty=1/
{
"query": {
"bool": {
"must": [
{
"match":
{ "name": "Thomas" }
},
{
"match":
{ "name": "Robert" }
}
],
"must_not": [
{
{
"match":
{ "type": "abc" }
}
]
}
}
}

这是在弹性搜索中创建AND场景的正确方法,还是有更好的查询来处理相同的输出。 我正在使用ES 2.1 感谢

1 个答案:

答案 0 :(得分:0)

鉴于您当前的目标:在句子中获取与Robert和Thomas匹配的所有文档,并且类型为xyz,您不应该在abc上使用must_not查询。如果有其他类型(例如ubv),您的查询也将获得与此类型匹配的文档。

您可以执行该查询:

{
    "query": {
        "bool": {
            "must": [
            {
                "match":
                { 
                      "name": {
                          "query": "Thomas Robert",
                          "operator": "and" 
                      }
                }
            },
            {
               "match":
               { 
                     "type": "xyz" 
               }
            }
         ]
      }
   }
}

顺便说一句,这些子句必须在bool查询中对查询进行评分。如果您只想过滤类型xyz,您应该使用:

{
    "query": {
        "bool": {
            "must": [
            {
                "match":
                { 
                      "name": {
                          "query": "Thomas Robert",
                          "operator": "and" 
                      }
                }
            }],
            "filter": [
                 {
                     "match": 
                     {
                         "type": "xyz"
                     }
                 }
            ]
      }
   }
}

此外,请查看术语级别查询与全文查询,以查看您真正需要的内容。如果您的"键入"如果不分析字段,则应使用术语查询而不是匹配来避免在匹配查询中进行分析。

https://www.elastic.co/guide/en/elasticsearch/reference/2.3/term-level-queries.html

相关问题