I have a field say birds name and I want to search all the birds which contain words.
public async Task<List<Bird>> GetBirdByName(string[] birdsName)
{
try
{
birdsName = birdsName.Select(x => x.ToLower()).ToArray();
FilterDefinition<Bird> filter = Builders<Bird>.Filter.In(r => r.BirdName, birdsName);
List<Bird> result = await _collection.Find(filter).ToListAsync();
return result;
}
catch (Exception ex)
{
await _logger.ExceptionLogAsync("BirdRepository.GetBirdByName", ex).ConfigureAwait(false);
}
return null;
}
I am not sure if this use the search index or not but I have created a search index on BirdName field and want to use it if it is not using it. Also how to check if my search index is being used or not?
I have found that we can use OR to search multiple inputs so if join the array with “OR” then will it cause any performance issue? Or I should not change the code
No, the Filter will not use a Search Index, if you mean an Atlas Search or Full Text index, it will use a standard Index, however.
If you want the query to hit a Text Index, use
// https://www.mongodb.com/docs/manual/reference/operator/query/text/
// This will treat each word as a logical OR
// Be careful with a combination like Red Robin, this will search for Red || Robin
Builders<Bird>.Filter.Text(
string.Join(' ', birdsName.Select(x => x.ToLower()))
)
If you want the query to hit a Search Index, use
// https://www.mongodb.com/docs/drivers/csharp/current/fundamentals/atlas-search/
// This will treat each word as a logical OR
// Be careful with a combination like Red Robin, this will search for Red || Robin
var filter = Builders<Bird>.Filter.Search(
string.Join(' ', birdsName.Select(x => x.ToLower()))
)
// NOTE: this must be fed into an Aggregate Pipeline
return _collection
.Aggregate()
.Search(filter)
ToListAsync();