繁体   English   中英

Elasticsearch 2.x,查询标签,并按标签重量对结果进行排序

[英]Elasticsearch 2.x, query for tag, and sort results by tag weigth

我正在使用Elasticsearch 2.3

我有一个书索引。 每本书都有标签,每个标签都有重量。 我想获取所有具有请求标签的图书,并按标签重量排序。

例如:

PUT book/book/0
{
    "name": "book 0",
    "tags": [
        {"t": "comedy", "w": 30},
        {"t": "drama","w": 20},
    ]
}

PUT book/book/1
{
    "name": "book 1",
    "tags": [
        {"t": "comedy", "w": 10},
        {"t": "drama","w": 5},
        {"t": "other","w": 50},
    ]
}

PUT book/book/2
    {
        "name": "book 2",
        "tags": [
            {"t": "comedy", "w": 5},
            {"t": "drama","w": 30},
        ]
    }

PUT book/book/3
    {
        "name": "book 3",
        "tags": [
            {"t": "comedy", "w": 5},
            {"t": "other","w": 30},
        ]
    }

我想搜索所有带有喜剧和戏剧标签的书籍。 结果顺序为:

  1. 图书0(20 + 30)
  2. 书2(30 + 5)
  3. 书1(10 + 5)

更新:我只想返回匹配两个标签的书(并仅按请求的标签排序)。 因此,如果我搜索“戏剧”和“喜剧”,则只会返回同时具有两个标签的书籍(在本例中为书籍0,书籍1,书籍2),并按请求的标签权重排序。

我怎么能得到这个? 任何查询的例子吗?

如果您始终想对所有权重求和,即使对于与查询不匹配的标记, 易卜拉欣的答案都是正确的。

如果只想考虑要搜索的标签的权重,则必须将tags作为nested对象编制索引。 这是因为,否则一切t S和w s的压扁成列表,在此过程中(描述丢失协会在这里 )。

然后,您可以使用nestednested查询中的function_score查询来仅汇总匹配标记的权重。 您将必须启用脚本

这是一个例子:

GET /book/_search
{
  "query": {
    "nested": {
      "path": "tags",
      "query": {
        "function_score": {
          "query": {
            "bool": {
              "filter": [
                {
                  "terms": {
                    "tags.t": [
                      "comedy",
                      "drama"
                    ]
                  }
                }
              ]
            }
          },
          "functions": [
            {
              "script_score": {
                "script": "return doc['tags.w'].value"
              }
            }
          ],
          "boost_mode": "replace"
        }
      },
      "score_mode": "sum"
    }
  }
}


===在@Eyal Ch的评论之后进行编辑===

如果只返回与两个标签都匹配的图书(在示例中为喜剧和戏剧),则它会变得更加复杂,因为每个搜索词都需要自己的nested查询。

这是一个例子:

 GET /book/_search { "query": { "bool": { "must": [ { "nested": { "path": "tags", "query": { "function_score": { "query": { "term": { "tags.t": { "value": "comedy" } } }, "functions": [ { "script_score": { "script": "return doc['tags.w'].value" } } ], "boost_mode": "replace" } } } }, { "nested": { "path": "tags", "query": { "function_score": { "query": { "term": { "tags.t": { "value": "drama" } } }, "functions": [ { "script_score": { "script": "return doc['tags.w'].value" } } ], "boost_mode": "replace" } } } } ] } } } 

尝试这个:

POST book/book/_search
{
    "query": {
        "match": {
           "tags.t": "comedy drama"
        }
    },
    "sort": [
       {
          "tags.w": {
             "order": "desc",
             "mode": "sum"
          }
       }
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM