Xiaohe Dong
Xiaohe Dong

Reputation: 5023

elasticsearch sorting unexpected null returned

I followed the doc https://www.elastic.co/guide/en/elasticsearch/guide/current/multi-fields.html to add sorting column for name field. Unfortunately, it is not working

These are the steps:

  1. add index mapping
PUT /staff
{
    "mappings": {
        "staff": {
            "properties": {
                "id": {
                    "type":   "string",
                    "index":  "not_analyzed"
                },
                "name": { 
                    "type":     "string",
                    "fields": {
                        "raw": { 
                            "type":  "string",
                            "index": "not_analyzed"
                        }
                    }
                }
            }
        }
    }
}
  1. Add document
POST /staff/list {
        "id": 5,
        "name": "abc" 
    }
  1. Search for the name.raw
POST /staff_change/_search
{
    "sort": "name.raw"
}

However, the sort field in the response return null

"_source": {
       "id": 5,
        "name": "abc"
    },
    "sort": [
        null
    ]
  }

I dont know why it is not working and I cant search relevant issue doc related this. Does someone come across this issue

Many thanks in advance

Upvotes: 2

Views: 1081

Answers (1)

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

Your mappings are incorrect. You create a mapping staff inside index staff and then index documents under mapping list inside index staff which works but with a dynamic mapping, not the one you added. In the end you are searching for all the documents in the index staff. Try this:

PUT /staff
{
    "mappings": {
        "list": {
            "properties": {
                "id": {
                    "type":   "string",
                    "index":  "not_analyzed"
                },
                "name": { 
                    "type":     "string",
                    "fields": {
                        "raw": { 
                            "type":  "string",
                            "index": "not_analyzed"
                        }
                    }
                }
            }
        }
    }
}

Then index:

POST /staff/list {
    "id": 5,
    "name": "abc aa" 
}

And query:

POST /staff/list/_search
{
    "sort": "name.raw"
}

Results in:

"hits": [
    {
        "sort": [
           "abc aa"
        ]
     }
...

Upvotes: 2

Related Questions