sorting - 通过匹配数组项进行 Elasticsearch 排序

标签 sorting elasticsearch

我在索引文档中有以下结构:

document1: "customLists":[{"id":8,"position":8},{"id":26,"position":2}]
document2: "customLists":[{"id":26,"position":1}]
document3: "customLists":[{"id":8,"position":1},{"id":26,"position":3}]

我能够使用匹配查询“customLists.id = 26”搜索属于给定列表的匹配文档。但我需要根据该列表中的位置值对文档进行排序,并忽略其他列表的位置。

因此预期的结果将按 document2、document1、document3 的顺序

数据结构是否适合这种排序,如何处理?

最佳答案

实现此目的的一种方法是将 customLists 的映射类型设置为 nested然后使用 nested fields 排序

示例:

1) 创建索引和映射

put test
put test/test/_mapping
{
   "properties": {
      "customLists": {
         "type": "nested",
         "properties": {
            "id": {
               "type": "integer"
            },
            "position": {
               "type": "integer"
            }
         }
      }
   }
}

2) 索引文档:

    put test/test/1 
    {
     "customLists":[{"id":8,"position":8},{"id":26,"position":2}]
    }
    put test/test/2
    {
    "customLists":[{"id":26,"position":1}] 
    }

   put test/test/3
   {
      "customLists":[{"id":8,"position":1},{"id":26,"position":3}]
   }

3) 查询以给定 id 按位置排序

post test/_search
    {
       "filter": {
          "nested": {
             "path": "customLists",
             "query": {
                "term": {
                   "customLists.id": {
                      "value": "26"
                   }
                }
             }
          }
       },
       "sort": [
          {
             "customLists.position": {
                "order": "asc",
                "mode": "min",
                "nested_filter": {
                   "term": {
                      "customLists.id": {
                         "value": "26"
                      }
                   }
                }
             }
          }
       ]
    }

关于sorting - 通过匹配数组项进行 Elasticsearch 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746662/

相关文章:

elasticsearch - 如何结合多个匹配查询?

nginx - 如何仅在Kibana中设置身份验证

amazon-web-services - 如何在AWS Elasticsearch中按模板明确分配分片大小?

c# - 如何使用 .NET 客户端 Elasticsearch 安全地重新创建索引

python - Elasticsearch-dsl 嵌套查询

java - 如何根据与另一个给定字符串的相似性对包含 1000 多个不同字符串的 ArrayList 进行排序

javascript - 根据一个属性的自定义优先级对数组进行排序

sorting - Business Catalyst 液体分选

sql - sql中的自定义排序

python - 如何对 pandas 中的字母数字字段进行排序?