Search with OR condition
This article shows how to obtain search results based on a "Logical OR" operation of two search clauses. It looks more like a two searches done in one go and the results combined.
To demonstrate the difference, lets first seach for all products which has a common parent.
Following example shows a method that will search for all the products under a given product group, (even products under sub-product groups are included)
/// <summary>
/// Searches for products (and variant groups) under a product group.
/// </summary>
/// <param name="languageId">The language id.</param>
/// <param name="productGroupId">The product group id.</param>
/// <param name="token">The token.</param>
/// <returns></returns>
public static IEnumerable<Guid> SearchForProducts(Guid languageId, Guid productGroupId, SecurityToken token)
{
IEnumerable<Guid> result = null;
var request = new QueryRequest(languageId, ProductCatalogSearchDomains.Products, token);
//search for all products and variant groups who has a parent with above product group id.
request.FilterTags.Add(new Tag(TagNames.ProductGroupTreeId, productGroupId));
var response = Solution.Instance.SearchService.Search(request);
if (response.Hits != null)
{
result = response.Hits.Select(x => new Guid(x.Id));
}
return result ?? new List<Guid>();
}
The above example searches only under a single product group. We can extend the search to return results searching under multiple product groups by using the OptionalTagClause as shown below.
/// <summary>
/// Searches for products (and variant groups) under all the product groups in parameter <paramref name="productGroupIds"/>
/// </summary>
/// <param name="languageId">The language id.</param>
/// <param name="productGroupIds">The product group ids.</param>
/// <param name="token">The token.</param>
/// <returns></returns>
public static IEnumerable<Guid> SearchForProducts(Guid languageId, List<Guid> productGroupIds, SecurityToken token)
{
IEnumerable<Guid> result = null;
var request = new QueryRequest(languageId, ProductCatalogSearchDomains.Products, token);
//search for all products and variant groups who has a parent with given groups.
var productGroupClause = new OptionalTagClause();
foreach (var item in productGroupIds)
{
productGroupClause.FilterTags.Add(new Tag(TagNames.ProductGroupTreeId, item));
}
request.FilterTags.Add(productGroupClause);
var response = Solution.Instance.SearchService.Search(request);
if (response.Hits != null)
{
result = response.Hits.Select(x => new Guid(x.Id));
}
return result ?? new List<Guid>();
}