Reputation: 7986
I know ElasticSearch is case-insensitive by default, and we can use mapping to enforce case-sensitive.
However, my requirement is that I need to toggle between case-insensitive and case-sensitive for a field. How should I approach this problem.
Upvotes: 1
Views: 2683
Reputation: 16172
You can use multi-fields to index the same field for case-sensitive and case insensitive searches.
Adding a working example with index data, mapping, search query, and search result
Index Mapping:
text
type field uses a standard analyzer (that can be used for case insensitive search) and the keyword
field uses keyword analyzer(that can be used for case insensitive search)
{
"mappings": {
"properties": {
"name": {
"type": "text",
"fields": { // note this
"raw": {
"type": "keyword"
}
}
}
}
}
}
Index Data:
{
"name": "john"
}
{
"name": "JOHN"
}
Search Query for Case sensitive search:
{
"query": {
"match": {
"name.raw": "JOHN"
}
}
}
Search Result:
"hits": [
{
"_index": "66679730",
"_type": "_doc",
"_id": "1",
"_score": 0.6931471,
"_source": {
"name": "JOHN"
}
}
]
Search Query for Case insensitive search:
{
"query": {
"match": {
"name": "JOHN"
}
}
}
Search Result will be
"hits": [
{
"_index": "66679730",
"_type": "_doc",
"_id": "1",
"_score": 0.18232156,
"_source": {
"name": "JOHN"
}
},
{
"_index": "66679730",
"_type": "_doc",
"_id": "2",
"_score": 0.18232156,
"_source": {
"name": "john"
}
}
]
Upvotes: 2