Dr T
Dr T

Reputation: 524

Elasticsearch keyword field sort returns wrong results

I am using Elasticsearch 7.9.0 on Windows.

I have the following mapping:

    "Name": {
      "type": "text",
      "fields": {
        "my-tokenizer": {
          "type": "text",
          "analyzer": "my-tokenizer"
        },
        "keyword": {
          "type": "keyword",
          "ignore_above": 256
        }
      }
    },

However, when I do this in my query my results are not sorted by name as I expect:

      "sort": [
        {
          "name.keyword": {"order": "asc" }
        }
      ],

My results contain a sort null value - is that significant? Does it tell us anything?

  "_type" : "_doc",
    "_id" : "ABC",
    "_score" : null,
    "_source" : {
      "name" : "Liverpool Football Club"
    },
    "sort" : [
      null
    ]
  },

(p.s. I have this as a decorator in my code Name = "name").

Upvotes: 1

Views: 1400

Answers (2)

Bhavya
Bhavya

Reputation: 16172

You created a mapping for the Name field (as mentioned above), but you have indexed documents for the name field. So probably documents are indexing with dynamic mapping.

Adding a working example with index data, search query, and search result. (Have not created any explicit mapping)

Index Data:

{
  "name": "Liverpool Football Club"
}
{
  "name": "quick brown f"
}
{
  "name": "this is a test"
}

Search Query:

{
  "sort": [
    {
      "name.keyword": "asc"
    }
  ]
}

Search Result:

"hits": [
      {
        "_index": "64977683",
        "_type": "_doc",
        "_id": "1",
        "_score": null,
        "_source": {
          "name": "Liverpool Football Club"
        },
        "sort": [
          "Liverpool Football Club"
        ]
      },
      {
        "_index": "64977683",
        "_type": "_doc",
        "_id": "3",
        "_score": null,
        "_source": {
          "name": "quick brown f"
        },
        "sort": [
          "quick brown f"
        ]
      },
      {
        "_index": "64977683",
        "_type": "_doc",
        "_id": "2",
        "_score": null,
        "_source": {
          "name": "this is a test"
        },
        "sort": [
          "this is a test"
        ]
      }
    ]

Upvotes: 1

Stephan Hahn
Stephan Hahn

Reputation: 11

Can you give the full mapping and index requests? Actually, I suspect that the documents are indexing with dynamic mapping and not using the one you defined.

Upvotes: 0

Related Questions