Ankur Rai
Ankur Rai

Reputation: 297

Elastic query to search eliminating spaces from mongodb data C#

I wanted to know if there is a way to search MongoDB data excluding space. My MongoDB has data such as -

"Element":"Ele1"
"Element":"Ele2"
"Element":"Ele 3"

And my search query has string excluding space i.e "Ele1,Ele2,Ele3". So When I pass "Ele3" to my search query it does not return any result. I am using ElasticSearch.net nuget. My code is something like this -

var elResp = await data.MultiSearchAsync(m => m
                    .Query(q => q
                    .Nested(n => n
                    .Path("Element")
                    .Query(qq => qq
                        .Bool(b => b
                            .Must(m1 => m1
                            .Term("Element.keyword", "Ele1")))))))

Is there anything I can do or I have to create an extra field in MongoDb which saves Element Value without space. So I can perform check from that. Thanks

Upvotes: 0

Views: 234

Answers (1)

mickl
mickl

Reputation: 49975

You'd achieve the best performance by creating extra field without spaces, however in MongoDB you can just use $regex to match both fields with and without spaces.

db.collection.find({ "Element": { $regex: /Ele\s*3/ } })

where \s is a whitespace and *means zero or more occurences. The more spaces you predict, the more you should consider adding a field without any spaces (because of performance), but /E\s*l\s*e\s*3/ will be still working for this case.

Upvotes: 1

Related Questions