7

i need to access document values stored in arrays from script. The order of the items in the array is important.

using doc['...'] to retrieve the array will mix up the order :-(

suppose a simple document like this

{
    "ar":[5,4,3,2,1]
}

retrieved using this Query:

{
  "query":{
    "match_all":{}
  },
  "script_fields": {
    "values": {
      "script": {
        "inline":"return doc['ar']"
      }
    }
  }
}

will return the array in reversed(sorted) order: [1,2,3,4,5] is there a way to prevent this behavior?

i can not resort to using _source because i need this in a "has_child" query, which does not support _source.

any ideas?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Holger Will
  • 7,228
  • 1
  • 31
  • 39

1 Answers1

3

Need to know how Elasticsearch indexed an array field.

similar question

To make field searchable, array field will be indexed in order, and you can not get the first value in script like doc['ar'][0]

if you want the origin array with order, you can use _source to get it like params._source['ar'], the results will be [5,4,3,2,1], but very slow than use doc

dddd1919
  • 868
  • 5
  • 13
  • as i said, i can not resort to using _source because this is in a "has_child" query which does not support _source :-( – Holger Will Sep 27 '17 at 13:41
  • I solve this problem by another way. My array size is fixed, so I change array field to object like `ar = {'1': 5, '2': 4, ....}`. when return `doc['ar']` ,I can get values by turn with object keys – dddd1919 Sep 28 '17 at 02:27
  • my arrays are not fixed, but this might work anyways. I'll give it a try. – Holger Will Sep 28 '17 at 02:49