Sorting based on initial term, don't include 2nd, 3rd term etc of the field

Suppose, we have below Details

Mapping:=>
{
"demo_index": {
"mappings": {
"my_doc": {
"properties": {
"first_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"second_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}

Data:=>
PUT demo_index/my_doc/1
{
"first_field":"Alpha Bita Gama",
"second_field":"XYZ"
}
PUT demo_index/my_doc/2
{
"first_field":"Bita1 Gama1 Alpha1",
"second_field":"PQR"
}
PUT demo_index/my_doc/3
{
"first_field":"Gama2 Alpha2 Bita2",
"second_field":"KLM"
}
PUT demo_index/my_doc/4
{
"first_field":"gama3 alpha3 bita3",
"second_field":"123"
}
PUT demo_index/my_doc/5
{
"first_field":"all bita gama",
"second_field":"123"
}


Problem:=> I can not change the mapping, Because It is running on production, and
1. I need to get the records begins with 'Al' or 'al' (It mean Camel Case, Upper Case, Lower Case record) .

2. Result should include initial term starting with 'Al' or 'al' only (It don't include 2nd, 3rd term etc of the field)
3. Based on below query I am getting only records begins with 'Al' not with 'al'
Query:=>
GET demo_index/_search
{
"_source": ["first_field","second_field"],
"query": {
"query_string": {
"fields": ["first_field.keyword","second_field"],
"query": "Al*"
}
}
}

Please suggest me possible modification in query except change in mapping.

Not at a computer where I can test this, but I think the only way to achieve what you want without a mapping change is to use a regex query and pin the regular expression to the beginning with ^:

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html#_standard_operators

That way only the first token in the string matches. Do note that regex queries are relatively more expensive than other queries.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.