1

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

> 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 点。

4

1 回答 1

1

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

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"
        ]
      }
    ]
  }
于 2019-09-28T13:33:22.507 回答