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.

2
  • 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? Commented Nov 14, 2018 at 3:29
  • student is not an array.. it's just an object Commented Nov 14, 2018 at 3:30

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@NiritLevi yes! thanks so much! I need to dive deeper in to Elasticsearch's documentation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.