【问题标题】:Elasticsearch: combine match_phrase and match in order to get only results for match_phrase (if any)Elasticsearch:结合 match_phrase 和 match 以便仅获取 match_phrase 的结果(如果有)
【发布时间】:2020-01-15 05:15:43
【问题描述】:

我有一个书籍索引,用于存储书籍的全文内容(删除了停用词,但这对我的问题并不重要)。 我有以下查询:

> GET /books/_search
>     {
>       "_source": {
>           "includes": ["author", "title"]
>       },
>       "query": {
>         "bool": {
>           "should": [
>             {
>               "match_phrase": {
>                 "body": "all happy families are alike"
>               }
>             },
>             {
>               "match": {
>                 "body": "all happy families are alike"
>               }
>             }
>           ]
>         }
>       }
>     }

我得到所有具有最高分数的完整字符串的文档的匹配,然后,具有较低分数的那些具有一个或多个匹配术语的文档:第一个匹配是'Anna Karenina',得分非常高,然后是任何书籍'快乐','家庭'在里面。 我想获得什么:

  1. 如果文档与条件“match_phrase”匹配,则仅获取此 结果(即只得到安娜卡列尼娜,丢弃其余的)
  2. 否则,以降分列出所有匹配的文档(预期行为)

我很难找到获得第 1 点的方法。

【问题讨论】:

    标签: elasticsearch match-phrase


    【解决方案1】:

    不能有条件地返回完全匹配和部分匹配。 您可以使用named queries 在客户端检查匹配是否完全/部分。

    GET books/_search
    {
      "query": {
        "bool": {
          "should": [
            {
              "match_phrase": {
                "body": {
                  "query": "all happy families are alike",
                  "_name":"exact_match"    ---> name of query(can be anything)
                }
              }
            },
            {
              "match": {
                "body":  {
                  "query": "all happy families are alike",
                  "_name":"partial_match"
                }
              }
            }
          ]
        }
      }
    }
    

    结果:

    "hits" : [
          {
            "_index" : "books",
            "_type" : "_doc",
            "_id" : "4i0MeG0BCVIM-bi3Fif1",
            "_score" : 4.1589947,
            "_source" : {
              "title" : "Anna Karenina",
              "body" : "all happy families are alike"
            },
            "matched_queries" : [   ---> returns name of queries where condition matched
              "exact_match",
              "partial_match"
            ]
          },
          {
            "_index" : "books",
            "_type" : "_doc",
            "_id" : "4y0MeG0BCVIM-bi3aScM",
            "_score" : 0.44216567,
            "_source" : {
              "title" : "book 1",
              "body" : "happy alike"
            },
            "matched_queries" : [  ---> returns name of queries where condition matched
              "partial_match"
            ]
          }
        ]
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多