Nested objects, hits, inner hits and sorting

(Seagullmouse) #1

As an example imagine

OuterObject contains nested NestedObject.

OuterObject1 contains NestedObject1, NestedObject2
OuterObject2 contains NestedObject3, NestedObject4

Desired Results (using a nested filter)
4 hits

  1. OuterObject1 and NestedObject1
  2. OuterObject1 and NestedObject2
  3. OuterObject2 and NestedObject3
  4. OuterObject2 and NestedObject4

If I use inner hits then the results look like this

  1. OuterObject1, inner_hits = NestedObject1, NestedObject2
  2. OuterObject2, inner_hits = NestedObject3, NestedObject4

I can then programmatically rewrite these results into the format I want and pretend the 2 hits are actually 4 hits.

The problem comes when I then try and sort my results by a field in NestedObject.

I want a sort that compares
NestedObject1 vs NestedObject2 vs NestedObject3 vs NestedObject4

The sort within inner_hits separately compares
NestedObject1 vs NestedObject2
NestedObject3 vs NestedObject4

Sorting using nested sort compares
NestedObject1 vs NestedObject3 (one NestedObject from OuterObject1 and one from OuterObject2)


  1. Am I misunderstanding Elasticsearch sorting?
  2. Is there a way to convert inner_hits to normal hits? I.e. so if I match 2 NestedObjects then I get 2 separate hits. This would avoid me programmatically 'pulling out' hits from inner_hits.
  3. How can I sort NestedObject1 vs NestedObject2 vs NestedObject3 vs NestedObject4

Thanks all in advance!

(Adrien Grand) #2

Elasticsearch doesn't support sorting nested documents. All that you can do is sorting root documents based on the values of nested documents.

Given the description of your issue, it looks like you should rather use denormalization than nested documents?

(Seagullmouse) #3

Thanks. Ok if there isn't a workaround in Elasticsearch itself then we will have a look at denormalising. Frustrating as it feels like the functionality is almost there.

Thank you

(system) #4