Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch: get for a substring in the value of a document field?

In mysql I can use the sql SELECT LEFT(field,4) from table to search 4 bytes of a field.

Elasticsearch has similar grammar?

like image 766
Dev Zhou Avatar asked Dec 18 '22 19:12

Dev Zhou


1 Answers

With ES, you can use script_fields in order to perform any script computation on existing fields.

In your case, this would translate to making a query like this:

{
    "query" : {
        "match_all": {}
    },
    "script_fields" : {
        "left_field" : {
            "script" : {
                "inline": "doc.field.value.substring(0, length)"
                "params": {
                    "length": 4
                }
            }
        }
    }
}

Then in your response you'll get a field named left_field which will contain the 4 left-most characters of the field value.

Also make sure to enable dynamic scripting in order for this to work.

like image 113
Val Avatar answered Apr 25 '23 20:04

Val