简体   繁体   English

ElasticSearch 排序数组大小不一致的结果

[英]ElasticSearch sort array size incoherent results

I am trying to sort by array size in ElasticSearch 7.1.我正在尝试按 ElasticSearch 7.1 中的数组大小排序。

I indexed the following data without creating any custom mapping:我在没有创建任何自定义映射的情况下索引了以下数据:

{
  "myarray": [{
    "field": {
      "value": "test"
    }
  }]
}

When I look at the mapping, it is giving me:当我查看映射时,它给了我:

{
  "properties": {
    "myarray": {
      "properties": {
        "field": {
          "properties": {
            "value": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        }
      }
    }
  }
}

Now I want to query the index and sort by the highest number of elements in myarray .现在我想查询索引并按myarray中最多的元素进行排序。 I have tried doing:我试过做:

{
  "sort": {
    "_script": {
        "type": "number",
        "order": "desc",
        "script": "doc.containsKey('myarray.field.value') ? doc['myarray.field.value'].values.size() : 0"
    }
  }
}

which gives me an error like Fielddata is disabled on text fields by default.[...] Alternatively use a keyword field instead .这给了我一个错误,例如Fielddata is disabled on text fields by default.[...] Alternatively use a keyword field instead So I try with所以我尝试

{
  "sort": {
    "_script": {
        "type": "number",
        "order": "desc",
        "script": "doc.containsKey('myarray.field.value.keyword') ? doc['myarray.field.value.keyword'].values.size() : 0"
    }
  }
}

which gives me the error Illegal list shortcut value [values].这给了我错误Illegal list shortcut value [values]. . . So then I tried with (removing the values keyword):所以然后我尝试了(删除values关键字):

{
  "sort": {
    "_script": {
        "type": "number",
        "order": "desc",
        "script": "doc.containsKey('myarray.field.value.keyword') ? doc['myarray.field.value.keyword'].size() : 0"
    }
  }
}

and it works, however I have some results that are sorted nicely and suddenly an element that should be at the top appears in the middle.它可以工作,但是我有一些排序很好的结果,突然一个应该在顶部的元素出现在中间。 Is that because it is sorting by the length of the value as a string and not the length of myarray ?那是因为它是按字符串的value的长度而不是myarray的长度排序的吗?

This is because text type mapping does not provide sorting, to add sorting you must map the array field with keyword type.这是因为文本类型映射不提供排序,要添加排序必须 map 带有关键字类型的数组字段。 For more info and syntax please refer this: https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-sort.html有关更多信息和语法,请参阅: https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-sort.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM