1

I'm new to Elasticsearch.

I have documents and each of them has a structure like this:

{
    "created_at": "2018-01-01 01:01:01",
    "student": {
        "first_name": "john",
        "last_name": "doe"
    },
    "parent": {
        "first_name": "susan",
        "last_name": "smile"
    }
}

I just want to sort those documents based on student.first_name using olivere/elastic package for go.

This is my query at the moment:

searchSvc = searchSvc.SortBy(elastic.NewFieldSort("student.first_name").Asc())

and I'm getting this error:

elastic: Error 400 (Bad Request): all shards failed [type=search_phase_execution_exception]

However when I tried sorting it by created_at, it's working.

searchSvc = searchSvc.SortBy(elastic.NewFieldSort("created_at").Asc())

I don't have any mapping in the index. (is this the problem?)

I tried searching for something like "Elasticsearch sort by nested object", but I always got questions that need to sort an array in the nested object.

mbuechmann
  • 5,413
  • 5
  • 27
  • 40
kkesley
  • 3,258
  • 1
  • 28
  • 55
  • It looks to me like `student` is an array. I am unfamiliar with go, but is there an array access operator `[]` or similar such as you might find in C or php etc? – pcgben Nov 14 '18 at 03:29
  • `student` is not an array.. it's just an object – kkesley Nov 14 '18 at 03:30

1 Answers1

1

It turns out that this is a beginner mistake.. You can't sort by text fields. I got it from here elasticsearch-dsl-py Sorting by Text() field

What you can do though, if you don't specify mappings, you can sort by the keyword property of the field.

searchSvc = searchSvc.SortBy(elastic.NewFieldSort("student.first_name.keyword").Asc())

And it works!

kkesley
  • 3,258
  • 1
  • 28
  • 55
  • The keyword field needs to be set in the mapping of the field (unless its a dynamic text field in which elastic produces a mapping with 'keyword' field and limits it to 256 chars , or something like that). The reason you cannot sort on a simple text field without a keyword-field or a fielddata=true , is because it is not a doc_value type of field, and its indexed values are produced from the standard text analyzer (like array with multiple words) rather than a single value. – Nirit Levi Nov 14 '18 at 09:15
  • @NiritLevi yes! thanks so much! I need to dive deeper in to Elasticsearch's documentation! – kkesley Nov 14 '18 at 22:01