Sorting an array of objects


(Aymen Fezai) #1

I am new to elasticsearch.
The documents I got look like this :

	user_name : "test", 
piInfo: {
	profile: {
		word_count: 535,
		word_count_message: "There were 535 words in the input.",
		processed_language: "en",
		personality: [
			{
				name: "Openness",
				category: "personality",
				percentile: 0.0015293409544490655,
				children: []
			},
			{
				name: "Conscientiousness",
				category: "personality",
				percentile: 0.6803430984001135,
				children: []
			}
		]
	}
}

I want to sort users (user_name) by personality (for example : "Conscientiousness.percentile")


(Zachary Tong) #2

If you want to keep that data structure, you'll need to map the "personality" field as a nested data type: https://www.elastic.co/guide/en/elasticsearch/reference/6.3/nested.html

Then you can sort on it using the nested sort: https://www.elastic.co/guide/en/elasticsearch/reference/6.3/search-request-sort.html#nested-sorting


(Aymen Fezai) #3

This what I came up with so far:

"query": {
            "nested": {
              "path": "piInfo.profile.personality",
              "query": {
                "bool": {
                  "must":
                    { "match": { "piInfo.profile.personality.name": "Openness" }} 
                }
              }
          }
        },
        "sort" : {
            "piInfo.profile.personality.percentile" : {
                "order" : "asc",
                "nested": {
                    "path": "piInfo.profile.personality",
                    "filter": {
                    "match": { "piInfo.profile.personality.name": "Openness" }
                    }
                }
            }
        }

And I got this error:

[nested] nested object under path [piInfo.profile.personality] is not of nested type

And that is logic because I didn't mapp it. I am taking data from an API and I am storing it as it is.

Is there a way around that?


(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.