【问题标题】:Elasticsearch - sort multi-index queryElasticsearch - 排序多索引查询
【发布时间】:2018-02-22 22:29:54
【问题描述】:

我正在使用 elasticsearch 构建自动完成搜索,因此我需要查询 3 个索引 postscommentsauthors。我有以下查询:

{
   "query":{
      "query_string":{
         "query":"something"
      }
   }
}

电话:

curl -X GET 'http://localhost:9200/posts,comments,authors/_search?pretty' -d '{
  "query": {
    "query_string": {
      "query": "something"
    }
  }
}'

我需要按特定的索引字段对结果进行排序,例如:

帖子索引有一个名为comments_count、cmets votes_count 和作者posts_count 的字段。比较帖子时,应按comments_count排序,cmets然后votes_count,作者然后posts_count

有可能做这样的事情吗?我不想将索引合并为一个,因为它们索引完全不同的文档。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    好吧,我的问题是,如果我按所有索引中不存在的字段进行排序,则不会返回文档。

    设法解决:

    {
       "_script":{
          "script":"type=doc['_type'].value;if(type=='posts'){return doc['comments_count'].value} else {return 0};",
          "type":"number",
          "order":"desc"
       }
    }
    

    至少现在显示文档,即使在底部。

    【讨论】:

    【解决方案2】:

    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

    使用ignore unmapped_type在查询多个索引且该字段在其他索引中不存在时忽略该字段。

    【讨论】:

    • 虽然这在理论上可以回答这个问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
    【解决方案3】:

    除了使用comments_countvotes_countposts_count,您还可以将相同名称(例如items_count)放入索引并执行常规排序:

    {
      "sort": [
        { "items_count": "desc" }
      ]
    }
    

    如果有其他实体缺少items_count,则可以选择ignore unmapped fields

    {
      "sort": [
        { "items_count": { "order": "desc", "unmapped_type": "long" } }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 2020-01-26
      • 2020-08-08
      • 2014-08-10
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多