通过匹配数组项进行弹性搜索排序 [英] Elasticsearch sorting by matching array item

查看:148
本文介绍了通过匹配数组项进行弹性搜索排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a following structure in indexed documents:

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搜索属于给定列表的匹配文档。但是,我需要根据该列表中的位置值对文档进行排序,并忽略其他列表的位置。

I am able to search matching documents that belong to a given list with match query "customLists.id = 26". But I need to sort the documents based on the position value within that list and ignore positions of the other lists.

所以预期的结果将按照document2,document1,document3的顺序

So the expected results would be in order of document2, document1, document3

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

Is the data structure suitable for this kind of sorting and how to handle this?

推荐答案

实现这一点的一种方法是设置<$ c的映射类型$ c> customLists as 嵌套,然后通过嵌套字段使用排序

One way to achieve this would be to set mapping type of customLists as nested and then use sorting by 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"
                      }
                   }
                }
             }
          }
       ]
    }

这篇关于通过匹配数组项进行弹性搜索排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆