Elasticsearch 按数组的第一个元素排序

Ula*_*ski 6 elasticsearch

我正在使用 Elasticsearch 5.5 并有一个具有此类映射的索引:

{
  "my_index": {
    "mappings": {
      "my_type": {
        "properties": {
          "title": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "my_array": {
            "properties": {
              "array": {
                "type": "float"
              },
              "length": {
                "type": "long"
              }
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想按标题搜索并按数组中的第一个值排序。另外,如果将第一个值设置为该字段,那就太好了_score。所以,我准备了这样的请求:

GET my_index/my_type/_search
{
    "query": {
      "term": {
        "title.keyword": "Shorts"
      }
    }, 
    "sort" : {
        "_script" : {
            "type" : "number",
            "script" : {
                "lang": "painless",
                "inline": "doc['my_array.array'][0]"
            },
            "order" : "asc"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是它不起作用。我觉得有什么东西缺失或者是错误的。

Nik*_*iev 1

正如安德烈_source在他的回答中指出的那样,你应该在你的无痛脚本中直接引用。

发生这种情况是因为 Lucene 索引(ElasticSearch 的构建基础)没有数组中值的原始顺序的概念。此外,数组并不像您期望的那样工作

对象数组并不像您期望的那样工作:您无法独立于数组中的其他对象来查询每个对象。

基本上,您是按列表中的随机数进行排序。

Andrei 建议使用_source,即读取原始 JSON 文档,解析它并从中提取所需的值(它会起作用)。但_source速度很慢(因为不是访问快速索引,而是每次从磁盘读取每个文档)。

您还有另外 2 个选择:

  • 将第一个元素作为单独的字段移动;
  • 使用nested数据类型并显式定义顺序。

希望有帮助!