如何查看布尔值中的哪些查询匹配?

时间:2016-01-14 06:09:21

标签: elasticsearch

我使用bool查询提供了多个查询。现在可能会发生其中一些可能具有匹配项,而某些查询可能在数据库中没有匹配项。我如何知道哪些查询匹配?

例如,我在这里有一个bool查询,其中有两个条件针对字段landMark

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "landMark": "wendys"
          }
        },
        {
          "match": {
            "landMark": "starbucks"
          }
        }
      ]
    }
  }
}

如果只有其中一个匹配文档,我怎么知道它们中的哪一个匹配?

2 个答案:

答案 0 :(得分:2)

您可以使用named queries来实现此目的。试试这个

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "landMark": {
              "query": "wendys",
              "_name": "wendy match"
            }
          }
        },
        {
          "match": {
            "landMark": {
              "query": "starbucks",
              "_name": "starbucks match"
            }
          }
        }
      ]
    }
  }
}

您可以使用任何_name。作为回应,你会得到类似的东西

"matched_queries": ["wendy match"]

这样您就可以判断哪个查询与该特定文档相匹配。

答案 1 :(得分:1)

命名查询肯定是要走的路。

LINK - https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-named-queries-and-filters.html

命名查询的想法很简单,您可以为每个查询标记一个名称,并在结果中显示每个文档匹配的所有标记。

curl -XPOST'http://localhost:9200/data/data'-d'{“landMark”:“wendys near starbucks”}'

curl -XPOST'http://localhost:9200/data/data'-d'{“landMark”:“wendys”}'

curl -XPOST'http://localhost:9200/data/data'-d'{“landMark”:“starbucks”}'

因此以这种方式创建您的查询 -

curl -XPOST 'http://localhost:9200/data/_search?pretty' -d '{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "landMark": {
              "query": "wendys",
              "_name": "wendy_is_a_match"
            }
          }
        },
        {
          "match": {
            "landMark": {
              "query": "starbucks",
              "_name": "starbuck_is_a_match"
            }
          }
        }
      ]
    }
  }
}'
{
  "took" : 7,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 0.581694,
    "hits" : [ {
      "_index" : "data",
      "_type" : "data",
      "_id" : "AVMCNNCY3OZJfBZCJ_tO",
      "_score" : 0.581694,
      "_source": { "landMark" : "wendys near starbucks" },
      "matched_queries" : [ "starbuck_is_a_match", "wendy_is_a_match" ]  ---> "Matched tags
    }, {
      "_index" : "data",
      "_type" : "data",
      "_id" : "AVMCNS0z3OZJfBZCJ_tQ",
      "_score" : 0.1519148,
      "_source": { "landMark" : "starbucks" },
      "matched_queries" : [ "starbuck_is_a_match" ]
    }, {
      "_index" : "data",
      "_type" : "data",
      "_id" : "AVMCNRsF3OZJfBZCJ_tP",
      "_score" : 0.04500804,
      "_source": { "landMark" : "wendys" },
      "matched_queries" : [ "wendy_is_a_match" ]
    } ]
  }
}