public override void Resolve(Q.Query <Displayable> query)
        {
            //ClaimsPrincipalDto.AddMarker("kpi.SearchQueryResolver.begin");

            //if (!string.IsNullOrEmpty(query.DataQueryToken))
            //{
            //    //NamedQueryFactory.Resolve(query);
            //    return;
            //}

            var builder        = new SearchQueryBuilder(query);
            var queryContainer = builder.GetQueryFor <Displayable>(query);

            var results = ElasticSearch.Search <ElasticTitleIndex>(queryContainer);

            //ClaimsPrincipalDto.Add("kpi.query", Encoding.UTF8.GetString(results.RequestInformation.Request));
            query.Items = new List <Displayable>();
            if (results.IsValid && results.Hits.Any())
            {
                foreach (var displayable in results.Documents.Select(item => item.MapToDisplayable()))
                {
                    query.Items.Add(displayable);
                }
                ExtractFilter(query, results);
                query.ResultSetCount = int.Parse(results.Total.ToString(CultureInfo.InvariantCulture));
            }
            // ClaimsPrincipalDto.AddMarker("kpi.SearchQueryResolver.end");
        }
 private static void ExtractFilter(Q.Query <Displayable> query, ISearchResponse <ElasticTitleIndex> results)
 {
     query.Filters = new ConcurrentDictionary <string, List <FacetFilter> >();
     lock (query.Filters)
     {
         if (query.ScopeId > 0)
         {
             query.Filters.TryAdd(SearchConstants.Ownership,
                                  GetOwnershipFacetFilter(results.Aggregations[SearchConstants.Ownership] as SingleBucketAggregate,
                                                          query.Facets));
         }
         query.Filters.TryAdd(SearchConstants.ListPrice,
                              GetListPriceFacetFilter(results.Aggregations[SearchConstants.ListPrice] as SingleBucketAggregate, query.Facets,
                                                      SearchConstants.MediaType));
         query.Filters.TryAdd(SearchConstants.MediaType,
                              GetFacetFilter(results.Aggregations[SearchConstants.MediaType] as SingleBucketAggregate, query.Facets,
                                             SearchConstants.MediaType));
         query.Filters.TryAdd(SearchConstants.Genre,
                              GetFacetFilter(results.Aggregations[SearchConstants.Genre] as SingleBucketAggregate, query.Facets,
                                             SearchConstants.Genre));
         query.Filters.TryAdd(SearchConstants.Audience,
                              GetFacetFilter(results.Aggregations[SearchConstants.Audience] as SingleBucketAggregate, query.Facets,
                                             SearchConstants.Audience));
         query.Filters.TryAdd(SearchConstants.Language,
                              GetFacetFilter(results.Aggregations[SearchConstants.Language] as SingleBucketAggregate, query.Facets,
                                             SearchConstants.Language));
         query.Filters.TryAdd(SearchConstants.UsageTerm,
                              GetFacetFilter(results.Aggregations[SearchConstants.UsageTerm] as SingleBucketAggregate, query.Facets,
                                             SearchConstants.UsageTerm));
         query.Filters.TryAdd(SearchConstants.Facets.ContentAdvisorySex,
                              GetFacetFilter(results.Aggregations[SearchConstants.ContentAdvisory] as SingleBucketAggregate,
                                             query.Facets,
                                             "sex"));
         query.Filters.TryAdd(SearchConstants.Facets.ContentAdvisoryLanguage,
                              GetFacetFilter(results.Aggregations[SearchConstants.ContentAdvisory] as SingleBucketAggregate,
                                             query.Facets,
                                             "language"));
         query.Filters.TryAdd(SearchConstants.Facets.ContentAdvisoryViolence,
                              GetFacetFilter(results.Aggregations[SearchConstants.ContentAdvisory] as SingleBucketAggregate,
                                             query.Facets,
                                             "violence"));
     }
 }
        public override SearchDescriptor <ElasticTitleIndex> GetQueryFor <TU>(Q.Query <TU> query)
        {
            QueryContainer queryContainer = null;

            if (!query.Criterion.Any())
            {
                queryContainer = GetDefaultQuery();
            }
            else
            {
                foreach (KeyValuePair <string, string> term in query.Criterion)
                {
                    if (_queryMap.ContainsKey(term.Key))
                    {
                        queryContainer &= _queryMap[term.Key](term);
                    }
                    else
                    {
                        queryContainer &= new MatchQuery()
                        {
                            Field = term.Key,
                            Query = term.Value
                        };
                    }
                }
            }

            //var queryContainer = new QueryContainer();
            //if (query.Facets != null && query.Facets.Count > 0)
            //{
            //    foreach (KeyValuePair<string, List<string>> facet in query.Facets)
            //    {
            //        if (_filterMap.ContainsKey(facet.Key))
            //        {
            //            QueryContainer &= _filterMap[facet.Key](facet);
            //        }
            //        else
            //        {
            //            QueryContainer &= Query<ElasticTitleIndex>.Terms(t=>t.Field(facet.Key).Terms(facet.Value));
            //        }
            //    }
            //}


            var searchDescriptor = new SearchDescriptor <ElasticTitleIndex>()
                                   .Query(q => queryContainer)
                                   .Size(query.PageSize)
                                   .From(query.PageIndex * query.PageSize).ExecuteOnPrimary().RequestCache(false)
                                   .Aggregations(
                a =>
                a
                .Filter(SearchConstants.ListPrice, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Histogram(SearchConstants.ListPrice, l => l.Field("pricing.price.list").Interval(50).MinimumDocumentCount(0).ExtendedBounds(0, 1000).OrderDescending("_key"))))
                .Filter(SearchConstants.Language, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms(SearchConstants.Language, l => l.Field(f => f.Language).MinimumDocumentCount(0).OrderAscending("_term").Size(30))))
                .Filter(SearchConstants.UsageTerm, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms(SearchConstants.UsageTerm, l => l.Field(f => f.UsageTerms).MinimumDocumentCount(0).OrderAscending("_term").Size(30))))
                .Filter(SearchConstants.MediaType, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms(SearchConstants.MediaType, l => l.Field(f => f.MediaType).MinimumDocumentCount(0).OrderAscending("_term"))))
                .Filter(SearchConstants.Genre, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms(SearchConstants.Genre, l => l.Field(f => f.Genres).MinimumDocumentCount(0).OrderAscending("_term").Size(50))))
                .Filter(SearchConstants.Audience, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms(SearchConstants.Audience, l => l.Field(f => f.Audience).MinimumDocumentCount(0).OrderAscending("_term").Size(30))))
                .Filter(SearchConstants.ContentAdvisory, fc => fc.Filter(f => queryContainer).Aggregations(agg => agg.Terms("sex", l => l.Field(ElasticFieldMapDictionary[SearchConstants.Facets.ContentAdvisorySex]).MinimumDocumentCount(0).OrderAscending("_term"))
                                                                                                           .Terms("language", l => l.Field(ElasticFieldMapDictionary[SearchConstants.Facets.ContentAdvisoryLanguage]).MinimumDocumentCount(0).OrderAscending("_term"))
                                                                                                           .Terms("violence", l => l.Field(ElasticFieldMapDictionary[SearchConstants.Facets.ContentAdvisoryViolence]).MinimumDocumentCount(0).OrderAscending("_term"))))
                .Filter(SearchConstants.Ownership, fc => fc.Filter(f => queryContainer)
                        //.Aggregations(agg =>
                        //    agg
                        //    .Filter(SearchConstants.Facets.Owned, f => f
                        //        .Filter(fi =>  fi.Bool(bo=>bo.Must(m=>m.HasChild<ElasticOwnershipIndex>(hc=>hc.Query(fil=>fil.Bool(b=>b.Must(mu=>mu.Term(t=>t.ScopeId, query.ScopeId),ra=>ra.Range(r=>r.OnField(of=>of.TotalCopies).Greater(0)) ))))))
                        //        ))
                        //    .Filter(SearchConstants.Facets.UnOwned, f => f
                        //        .Filter(fi =>  fi.Bool(bo=>bo.MustNot(m=>m.HasChild<ElasticOwnershipIndex>(hc=>hc.Query(fil=>fil.Bool(b=>b.Must(mu=>mu.Term(t=>t.ScopeId, query.ScopeId),ra=>ra.Range(r=>r.OnField(of=>of.TotalCopies).Greater(0)) ))))))
                        //        ))
                        //)
                        ))
            ;

            //add sort order
            if (!string.IsNullOrEmpty(query.SortBy) && _sortDictionary.ContainsKey(query.SortBy))
            {
                searchDescriptor.Sort(s => s.Field(f => f.Field(_sortDictionary[query.SortBy]).MissingLast().Order(query.SortOrder.ToLower() == "desc" ? SortOrder.Descending : SortOrder.Ascending)));
            }
            return(searchDescriptor);
        }
 public SearchQueryBuilder(Q.Query <Displayable> query)
 {
     ScopeId = query.ScopeId;
 }