Waku-2
Waku-2

Reputation: 1196

elasticsearch searching where nth character of a field matches the parameter

Elasticsearch index has json docs like this

{
  id: ABC120379013
  name: Matlo Jonipa
  jobs: {nested data}
}

When defining index schema, I register id as keyword.

Now I need to write a query that can return all docs where 4th char in the id field value is digit 9.

# matched docs
id: ABC920379013,
id: Zxr900013000
...

I have two questions for this usecase.

1- Am I indexing it right when I set id as a keyword field? I feel I should be using some analyzer but I don't know which one.

2- Can someone guide me how to write a query to match nth char of a field?

I can use this regex to match a string whose 4th character is 9 but can I use it in an elasticsearch query?

/^...9.*$/
or
/^.{3}9.*$/

Upvotes: 1

Views: 344

Answers (1)

Kamal Kunjapur
Kamal Kunjapur

Reputation: 8840

Below query would help your use case. I've used Script Query.

Also, yes you are doing it right, you need to make sure that the field id would be of type keyword. Note that keyword type doesn't make use of analyzers.

POST regexindex/_search
{
  "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "source": "doc['id'].value.indexOf('9') == 3",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

I've mentioned .indexOf('9') == 3 because index starts from 0

Upvotes: 1

Related Questions