elasticsearch 在弹性域搜索中按嵌套字段排序

bkhjykvo  于 2022-12-03  发布在  ElasticSearch
关注(0)|答案(1)|浏览(149)

如果我有一个像这样的数据结构

[{"_id" 1 
 "scores" [{"student_id": 1, "score": 100"}, {"student_id": 2, "score": 80"}
 ]}, 
{"_id" 2
 "scores" [{"student_id": 1, "score": 20"}, {"student_id": 2, "score": 90"}
 ]}]

是否可以按student_1的分数或student_2的分数对此数据集进行排序?
例如,如果我按学生1的分数降序排序,我将得到文档1,2,但如果我按学生2的分数降序排序,我将得到2,1。
我可以重新排列数据,但我不想使用另一个索引,因为有一堆元数据没有包括在上面的简洁。谢谢!

0wi1tuuw

0wi1tuuw1#

是的,这是可能的。你必须为你的分数使用“嵌套”字段类型,这样你就可以保持每个student_id和它的分数之间的关系。
你可以读到我写的一篇关于这个主题的文章:https://opster.com/guides/elasticsearch/data-architecture/elasticsearch-nested-field-object-field/
现在举个例子:

Map

PUT test_students
{
  "mappings": {
    "properties": {
      "scores": {
        "type": "nested",
        "properties": {
          "student_id": {
            "type": "keyword"
          },
          "score": {
            "type": "long"
          }
        }
      }
    }
  }
}

文件

PUT test_students/_doc/1
{
  "scores": [{"student_id": 1, "score": 100}, {"student_id": 2, "score": 80}]
}

PUT test_students/_doc/2
{
  "scores": [{"student_id": 1, "score": 20}, {"student_id": 2, "score": 90}]
}

查询

POST test_students/_search
{
   "sort" : [
       {
          "scores.score" : {
             "mode" :  "max",
             "order" : "desc",
             "nested": {
                "path": "scores",
                "filter": {
                   "term" : { "scores.student_id" : "2" }
                }
             }
          }
       }
    ]
}

相关问题