Reputation: 334
I'm new to using elastic search. I'm using the .NET client version 8.12 (nuget package: Elastic.Clients.Elasticsearch), I'm trying to send a query based on parameters. Only add the condition if the parameter value exists. Below is the code for the query:
public class ProductSearchDto
{
public string? Term { get; set; }
public string? CategoryId { get; set; }
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
public int? Stars { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}
The index class:
public class ProductIndex
{
public string Id { get; set; }
public decimal Price { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string CategoryId { get; set; }
public int Stars { get; set; }
public DateTime IndexedAt { get; set; } = DateTime.UtcNow;
}
Also, for the generation of the query below is the code that calls elastic search:
public async Task<List<ProductIndex>> Search(ProductSearchDto searchDto)
{
QueryDescriptor<ProductIndex> query = new QueryDescriptor<ProductIndex>();
if (!string.IsNullOrEmpty(searchDto.Term))
{
query
.Match(r => r.Field(y => y.Description).Query(searchDto.Term));
}
if (!string.IsNullOrEmpty(searchDto.CategoryId))
{
query
.Match(r => r.Field(y => y.CategoryId).Query(searchDto.CategoryId));
}
if (searchDto.Stars.HasValue)
{
query
.Match(r => r.Field(y => y.Stars).Query(searchDto.Stars.Value.ToString()));
}
if (searchDto.PriceFrom.HasValue)
{
query
.Range(r => r.NumberRange(z => z.Field(t => t.Price).From(searchDto.PriceFrom)
.To(searchDto.PriceTo)));
}
var result = await _searchOperation.SearchIndexElastic<ProductIndex>
(query);
return result;
}
I debugged the query and it always just sending one parameter although other conditions are still active. Any other ways?
Upvotes: 1
Views: 265