Search code examples
javascriptsortingelasticsearchdataprovider

Enable ascending and descending sorting of numbers that are of the keyword type (Elasticsearch)


My task is to sort documents in ascending and descending order, but 'number' must remain of the keyword type. I read other posts on a similar topic, and tried to add an 'number' of type integer, but I didn't succeed and the index crashes. I am attaching the current configuration in the esMapping.js file.

Is there a way to fix this esMapping.js file so that ascending and descending sorting works?

"settings": {
    "analysis": {
        "analyzer": {
            "document_number_analyzer": {
                "type": "custom",
                "tokenizer": "document_number_tokenizer"
            }
        },
        "tokenizer": {
            "document_number_tokenizer": {
                "type": "pattern",
                "pattern": "-0*([1-9][0-9]*)\/",
                "group": 1
            }
        },
    }
}

Mapping:

"number": {
            "type": "keyword",
            "copy_to": [
                "_summary"
            ],
            "fields": {
                "sequenceNumber": {
                    "type": "text",
                    "analyzer": "document_number_analyzer"
                }
            }
        }

EDIT:

Error after using integer sub-field to sort documents:

022-05-18 11:33:32.5830 [ERROR] ESIndexerLogger Failed to commit bulk. Errors:
index returned 400 _index: adama_gen_ro_importdocument _type: _doc _id: 4c616067-4beb-4484-83cc-7eb9d36eb175 _version: 0 error: Type: mapper_parsing_exception Reason: "failed to parse field [number.sequenceNumber] of type [integer] in document with id '4c616067-4beb-4484-83cc-7eb9d36eb175'. Preview of field's value: 'BS-000011/2022'" CausedBy: "Type: number_format_exception Reason: "For input string: "BS-000011/2022"""

Solution

  • Your mapping needs to be like this:

        "number": {
            "type": "keyword",
            "copy_to": [
                "_summary"
            ],
            "fields": {
                "sequenceNumber": {
                    "type": "integer"
                }
            }
        }
    

    And then you can simply sort by number.sequenceNumber