/// <summary>
    /// Returns list item with range values.
    /// </summary>
    private ListItem GetRangeListItem(FacetResult facetResult)
    {
        string from = facetResult.From?.ToString() ?? "0";
        string to   = facetResult.To?.ToString() ?? string.Empty;

        return(new ListItem($"{from}-{to} ({facetResult.Count})", $"{from};{to}"));
    }
コード例 #2
0
        public async Task StartAsync(IDialogContext context)
        {
            try
            {
                FacetResult facetResult = await searchService.FetchFacets();

                if (facetResult.searchfacets.Era.Length != 0)
                {
                    List <string> eras = new List <string>();
                    foreach (Era era in facetResult.searchfacets.Era)
                    {
                        eras.Add($"{era.value} ({era.count})");
                    }
                    PromptDialog.Choice(context, AfterMenuSelection, eras, "Which era of music are you interested in?");
                }
                else
                {
                    await context.PostAsync("I couldn't find any genres to show you");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error when faceting by era: {e}");
                context.Done <object>(null);
            }
        }
コード例 #3
0
        public async Task StartAsync(IDialogContext context)
        {
            if (string.IsNullOrWhiteSpace(this.category))
            {
                FacetResult facetResult = await this.searchService.FetchFacets();

                if (facetResult.Facets.Category.Length != 0)
                {
                    List <string> categories = new List <string>();
                    foreach (Category category in facetResult.Facets.Category)
                    {
                        categories.Add($"{category.Value} ({category.Count})");
                    }

                    PromptDialog.Choice(context, this.AfterMenuSelection, categories, "Let\'s see if I can find something in the knowledge for you. Which category is your question about?");
                }
            }
            else
            {
                SearchResult searchResult = await this.searchService.SearchByCategory(this.category);

                await CardUtil.ShowSearchResults(context, searchResult, $"Sorry, I could not find any results in the knowledge base for _'{this.category}'_");

                context.Done <object>(null);
            }
        }
コード例 #4
0
        public virtual void TestOverlappedEndStart()
        {
            Directory             d     = NewDirectory();
            var                   w     = new RandomIndexWriter(Random(), d, Similarity, TimeZone);
            Document              doc   = new Document();
            NumericDocValuesField field = new NumericDocValuesField("field", 0L);

            doc.Add(field);
            for (long l = 0; l < 100; l++)
            {
                field.SetInt64Value(l);
                w.AddDocument(doc);
            }
            field.SetInt64Value(long.MaxValue);
            w.AddDocument(doc);

            IndexReader r = w.Reader;

            w.Dispose();

            FacetsCollector fc = new FacetsCollector();
            IndexSearcher   s  = NewSearcher(r);

            s.Search(new MatchAllDocsQuery(), fc);

            Facets facets = new Int64RangeFacetCounts("field", fc, new Int64Range("0-10", 0L, true, 10L, true), new Int64Range("10-20", 10L, true, 20L, true), new Int64Range("20-30", 20L, true, 30L, true), new Int64Range("30-40", 30L, true, 40L, true));

            FacetResult result = facets.GetTopChildren(10, "field");

            Assert.AreEqual("dim=field path=[] value=41 childCount=4\n  0-10 (11)\n  10-20 (11)\n  20-30 (11)\n  30-40 (11)\n", result.ToString());

            r.Dispose();
            d.Dispose();
        }
コード例 #5
0
        /// <summary>User runs a query and aggregates facets.</summary>
        private FacetResult Search()
        {
            using DirectoryReader indexReader = DirectoryReader.Open(indexDir);
            using TaxonomyReader taxoReader   = new DirectoryTaxonomyReader(taxoDir);
            IndexSearcher searcher = new IndexSearcher(indexReader);

            // Aggregate categories by an expression that combines the document's score
            // and its popularity field
            Expression     expr     = JavascriptCompiler.Compile("_score * sqrt(popularity)");
            SimpleBindings bindings = new SimpleBindings
            {
                new SortField("_score", SortFieldType.SCORE),     // the score of the document
                new SortField("popularity", SortFieldType.INT64), // the value of the 'popularity' field
            };

            // Aggregates the facet values
            FacetsCollector fc = new FacetsCollector(true);

            // MatchAllDocsQuery is for "browsing" (counts facets
            // for all non-deleted docs in the index); normally
            // you'd use a "normal" query:
            FacetsCollector.Search(searcher, new MatchAllDocsQuery(), 10, fc);

            // Retrieve results
            Facets      facets = new TaxonomyFacetSumValueSource(taxoReader, config, fc, expr.GetValueSource(bindings));
            FacetResult result = facets.GetTopChildren(10, "A");

            return(result);
        }
コード例 #6
0
        public virtual void TestBigNumResults()
        {
            DirectoryReader indexReader = DirectoryReader.Open(indexDir);
            var taxoReader = new DirectoryTaxonomyReader(taxoDir);
            IndexSearcher searcher = NewSearcher(indexReader);

            FacetsCollector sfc = new FacetsCollector();
            searcher.Search(new MatchAllDocsQuery(), sfc);

            Facets facets = GetTaxonomyFacetCounts(taxoReader, Config, sfc);

            FacetResult result = facets.GetTopChildren(int.MaxValue, CP_A);
            Assert.AreEqual(-1, (int)result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.label], labelValue.value);
            }
            result = facets.GetTopChildren(int.MaxValue, CP_B);
            Assert.AreEqual(allExpectedCounts[CP_B], result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.label], labelValue.value);
            }

            IOUtils.Close(indexReader, taxoReader);
        }
コード例 #7
0
        public virtual void TestDifferentNumResults()
        {
            // test the collector w/ FacetRequests and different numResults
            DirectoryReader indexReader = DirectoryReader.Open(indexDir);
            var             taxoReader  = new DirectoryTaxonomyReader(taxoDir);
            IndexSearcher   searcher    = NewSearcher(indexReader);

            FacetsCollector sfc = new FacetsCollector();
            TermQuery       q   = new TermQuery(A);

            searcher.Search(q, sfc);
            Facets      facets = GetTaxonomyFacetCounts(taxoReader, Config, sfc);
            FacetResult result = facets.GetTopChildren(NUM_CHILDREN_CP_A, CP_A);

            Assert.AreEqual(-1, (int)result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(termExpectedCounts[CP_A + "/" + labelValue.Label], labelValue.Value);
            }
            result = facets.GetTopChildren(NUM_CHILDREN_CP_B, CP_B);
            Assert.AreEqual(termExpectedCounts[CP_B], result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(termExpectedCounts[CP_B + "/" + labelValue.Label], labelValue.Value);
            }

            IOUtils.Dispose(indexReader, taxoReader);
        }
コード例 #8
0
        public override List <FacetResult> GetAllDims(int topN)
        {
            int ord = children[TaxonomyReader.ROOT_ORDINAL];
            IList <FacetResult> results = new List <FacetResult>();

            while (ord != TaxonomyReader.INVALID_ORDINAL)
            {
                string    dim       = taxoReader.GetPath(ord).Components[0];
                DimConfig dimConfig = config.GetDimConfig(dim);
                if (dimConfig.IndexFieldName.Equals(indexFieldName))
                {
                    FacetResult result = GetTopChildren(topN, dim);
                    if (result != null)
                    {
                        results.Add(result);
                    }
                }
                ord = siblings[ord];
            }

            // Sort by highest value, tie break by dim:
            var resultArray = results.ToList();

            resultArray.Sort(BY_VALUE_THEN_DIM);
            return(resultArray);
        }
コード例 #9
0
        public override IList <FacetResult> GetAllDims(int topN)
        {
            List <FacetResult> results = new List <FacetResult>();

            foreach (KeyValuePair <string, OrdRange> ent in state.PrefixToOrdRange)
            {
                FacetResult fr = GetDim(ent.Key, ent.Value, topN);
                if (fr != null)
                {
                    results.Add(fr);
                }
            }

            // Sort by highest count:
            results.Sort(Comparer <FacetResult> .Create((a, b) =>
            {
                if ((int)a.Value > (int)b.Value)
                {
                    return(-1);
                }
                else if ((int)b.Value > (int)a.Value)
                {
                    return(1);
                }
                else
                {
                    return(a.Dim.CompareToOrdinal(b.Dim));
                }
            }));
            return(results);
        }
コード例 #10
0
        private static List <Models.API.FacetResult> BuildFacets(ISearchResults searchResult, Tab tab)
        {
            var facetResults = new List <Models.API.FacetResult>();

            foreach (var facetConfiguration in tab.Facets)
            {
                ISearchResultFacet facet = searchResult.Facets.Where(x => x.Definition.FieldName == facetConfiguration.FieldName).FirstOrDefault();
                if (facet != null)
                {
                    FacetResult facetResult = new FacetResult();
                    facetResult.Values    = new List <FacetValue>();
                    facetResult.Name      = facetConfiguration.Name;
                    facetResult.FieldName = facetConfiguration.FieldName;

                    foreach (var facetValue in facet.Values)
                    {
                        FacetValue facetResultValue = new FacetValue();
                        facetResultValue.Count    = facetValue.Count;
                        facetResultValue.Name     = facetValue.Value.ToString();
                        facetResultValue.Selected = facetValue.Selected;
                        facetResultValue.Value    = facetValue.Value.ToString();
                        facetResult.Values.Add(facetResultValue);
                    }
                    facetResult = SortFacetValues(facetConfiguration, facetResult);
                    facetResults.Add(facetResult);
                }
            }
            return(facetResults);
        }
コード例 #11
0
        public virtual void TestNoParents()
        {
            DirectoryReader indexReader = DirectoryReader.Open(indexDir);
            var             taxoReader  = new DirectoryTaxonomyReader(taxoDir);
            IndexSearcher   searcher    = NewSearcher(indexReader);

            var sfc = new FacetsCollector();

            searcher.Search(new MatchAllDocsQuery(), sfc);

            Facets facets = GetTaxonomyFacetCounts(taxoReader, Config, sfc);

            FacetResult result = facets.GetTopChildren(NUM_CHILDREN_CP_C, CP_C);

            Assert.AreEqual(allExpectedCounts[CP_C], result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_C + "/" + labelValue.Label], labelValue.Value);
            }
            result = facets.GetTopChildren(NUM_CHILDREN_CP_D, CP_D);
            Assert.AreEqual(allExpectedCounts[CP_C], result.Value);
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_D + "/" + labelValue.Label], labelValue.Value);
            }

            IOUtils.Dispose(indexReader, taxoReader);
        }
コード例 #12
0
        public virtual void TestAllCounts()
        {
            DirectoryReader indexReader = DirectoryReader.Open(indexDir);
            var taxoReader = new DirectoryTaxonomyReader(taxoDir);
            IndexSearcher searcher = NewSearcher(indexReader);

            FacetsCollector sfc = new FacetsCollector();
            searcher.Search(new MatchAllDocsQuery(), sfc);

            Facets facets = GetTaxonomyFacetCounts(taxoReader, Config, sfc);

            FacetResult result = facets.GetTopChildren(NUM_CHILDREN_CP_A, CP_A);
            Assert.AreEqual(-1, (int)result.Value);
            int prevValue = int.MaxValue;
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.label], labelValue.value);
                Assert.True((int)labelValue.value <= prevValue, "wrong sort order of sub results: labelValue.value=" + labelValue.value + " prevValue=" + prevValue);
                prevValue = (int)labelValue.value;
            }

            result = facets.GetTopChildren(NUM_CHILDREN_CP_B, CP_B);
            Assert.AreEqual(allExpectedCounts[CP_B], result.Value);
            prevValue = int.MaxValue;
            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.label], labelValue.value);
                Assert.True((int)labelValue.value <= prevValue, "wrong sort order of sub results: labelValue.value=" + labelValue.value + " prevValue=" + prevValue);
                prevValue = (int)labelValue.value;
            }

            IOUtils.Close(indexReader, taxoReader);
        }
コード例 #13
0
        public virtual void TestLongMinMax()
        {
            Directory             d     = NewDirectory();
            RandomIndexWriter     w     = new RandomIndexWriter(Random(), d, Similarity, TimeZone);
            Document              doc   = new Document();
            NumericDocValuesField field = new NumericDocValuesField("field", 0L);

            doc.Add(field);
            field.SetInt64Value(long.MinValue);
            w.AddDocument(doc);
            field.SetInt64Value(0);
            w.AddDocument(doc);
            field.SetInt64Value(long.MaxValue);
            w.AddDocument(doc);

            IndexReader r = w.Reader;

            w.Dispose();

            FacetsCollector fc = new FacetsCollector();
            IndexSearcher   s  = NewSearcher(r);

            s.Search(new MatchAllDocsQuery(), fc);

            Facets facets = new Int64RangeFacetCounts("field", fc, new Int64Range("min", long.MinValue, true, long.MinValue, true), new Int64Range("max", long.MaxValue, true, long.MaxValue, true), new Int64Range("all0", long.MinValue, true, long.MaxValue, true), new Int64Range("all1", long.MinValue, false, long.MaxValue, true), new Int64Range("all2", long.MinValue, true, long.MaxValue, false), new Int64Range("all3", long.MinValue, false, long.MaxValue, false));

            FacetResult result = facets.GetTopChildren(10, "field");

            Assert.AreEqual("dim=field path=[] value=3 childCount=6\n  min (1)\n  max (1)\n  all0 (3)\n  all1 (2)\n  all2 (2)\n  all3 (1)\n", result.ToString());

            r.Dispose();
            d.Dispose();
        }
コード例 #14
0
        public void TestSimple()
        {
            using RangeFacetsExample example = new RangeFacetsExample();
            example.Index();
            FacetResult result = example.Search();

            assertEquals("dim=timestamp path=[] value=87 childCount=3\n  Past hour (4)\n  Past six hours (22)\n  Past day (87)\n", result.toString());
        }
コード例 #15
0
        public void TestSimple()
        {
            using DistanceFacetsExample example = new DistanceFacetsExample();
            example.Index();
            FacetResult result = example.Search();

            assertEquals("dim=field path=[] value=3 childCount=4\n  < 1 km (1)\n  < 2 km (2)\n  < 5 km (2)\n  < 10 km (3)\n", result.toString());
        }
コード例 #16
0
 private static GenericFacet ToFacet(FacetResult facetResult)
 {
     return(new GenericFacet
     {
         Value = facetResult.Value,
         Count = facetResult.Count.Value
     });
 }
コード例 #17
0
 public bool CanMergeFacet(FacetResult result)
 {
     return(CompareFacetField(result.Value, Value) &&
            CompareFacetField(result.To, To) &&
            CompareFacetField(result.From, From) &&
            CompareFacetField(result.FacetType, FacetType) &&
            result.Count.HasValue);
 }
コード例 #18
0
        private static void CheckResults(FacetedQueryResult result)
        {
            Assert.Contains("Brand", result.Results.Select(x => x.Key));
            FacetResult facetResult = result.Results["Brand"];

            Assert.Equal(1, facetResult.Values.Count);
            facetResult.Values[0] = new FacetValue {
                Range = "mybrand1", Hits = 1
            };
        }
コード例 #19
0
        private static void CheckResults(Dictionary <string, FacetResult> result)
        {
            Assert.Contains("Brand", result.Select(x => x.Key));
            FacetResult facetResult = result["Brand"];

            Assert.Equal(1, facetResult.Values.Count);
            facetResult.Values[0] = new FacetValue {
                Range = "mybrand1", Count = 1
            };
        }
コード例 #20
0
        public virtual void TestMultiValuedHierarchy()
        {
            Store.Directory         dir        = NewDirectory();
            Store.Directory         taxoDir    = NewDirectory();
            DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, OpenMode.CREATE);
            FacetsConfig            config     = new FacetsConfig();

            config.SetHierarchical("a", true);
            config.SetMultiValued("a", true);
            RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
                this,
#endif
                Random, dir);

            Document doc = new Document();

            doc.Add(NewTextField("field", "text", Field.Store.NO));
            doc.Add(new FacetField("a", "path", "x"));
            doc.Add(new FacetField("a", "path", "y"));
            writer.AddDocument(config.Build(taxoWriter, doc));

            // NRT open
            IndexSearcher searcher = NewSearcher(writer.GetReader());

            // NRT open
            var taxoReader = new DirectoryTaxonomyReader(taxoWriter);

            // Aggregate the facet counts:
            FacetsCollector c = new FacetsCollector();

            // MatchAllDocsQuery is for "browsing" (counts facets
            // for all non-deleted docs in the index); normally
            // you'd use a "normal" query, and use MultiCollector to
            // wrap collecting the "normal" hits and also facets:
            searcher.Search(new MatchAllDocsQuery(), c);
            Facets facets = GetTaxonomyFacetCounts(taxoReader, config, c);

            try
            {
                facets.GetSpecificValue("a");
                fail("didn't hit expected exception");
            }
            catch (Exception iae) when(iae.IsIllegalArgumentException())
            {
                // expected
            }

            FacetResult result = facets.GetTopChildren(10, "a");

            Assert.AreEqual(1, result.LabelValues.Length);
            Assert.AreEqual(1, (int)result.LabelValues[0].Value);

            IOUtils.Dispose(writer, taxoWriter, searcher.IndexReader, taxoReader, dir, taxoDir);
        }
コード例 #21
0
        public static Dictionary <string, FacetResult> Parse(IReadOnlyList <Facet> facets, out Dictionary <string, Facet> defaultFacets, out Dictionary <string, List <ParsedRange> > rangeFacets)
        {
            var results = new Dictionary <string, FacetResult>();

            defaultFacets = new Dictionary <string, Facet>();
            rangeFacets   = new Dictionary <string, List <ParsedRange> >();
            foreach (var facet in facets)
            {
                var key = string.IsNullOrWhiteSpace(facet.DisplayName) ? facet.Name : facet.DisplayName;

                defaultFacets[key] = facet;
                if (facet.Aggregation != FacetAggregation.Count && facet.Aggregation != FacetAggregation.None)
                {
                    if (string.IsNullOrEmpty(facet.AggregationField))
                    {
                        throw new InvalidOperationException($"Facet {facet.Name} cannot have aggregation set to {facet.Aggregation} without having a value in AggregationField");
                    }

                    if (facet.AggregationField.EndsWith(Constants.Indexing.Fields.RangeFieldSuffix) == false)
                    {
                        if (FacetedQueryHelper.IsAggregationTypeNumerical(facet.AggregationType))
                        {
                            facet.AggregationField = facet.AggregationField + Constants.Indexing.Fields.RangeFieldSuffix;
                        }
                    }
                }

                switch (facet.Mode)
                {
                case FacetMode.Default:
                    results[key] = new FacetResult();
                    break;

                case FacetMode.Ranges:
                    rangeFacets[key] = facet.Ranges
                                       .Select(range => ParseRange(facet.Name, range))
                                       .ToList();

                    results[key] = new FacetResult
                    {
                        Values = facet.Ranges
                                 .Select(range => new FacetValue {
                            Range = range
                        })
                                 .ToList()
                    };
                    break;

                default:
                    throw new ArgumentException(string.Format("Could not understand '{0}'", facet.Mode));
                }
            }

            return(results);
        }
コード例 #22
0
        public HowToPerformQueriesLazily()
        {
            using (var store = new DocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    #region lazy_2
                    Lazy <IEnumerable <Employee> > employeesLazy = session
                                                                   .Query <Employee>()
                                                                   .Where(x => x.FirstName == "Robert")
                                                                   .Lazily();

                    IEnumerable <Employee> employees = employeesLazy.Value; // query will be executed here
                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_5
                    Lazy <int> countLazy = session
                                           .Query <Employee>()
                                           .Where(x => x.FirstName == "Robert")
                                           .CountLazily();

                    int count = countLazy.Value; // query will be executed here
                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_7
                    Lazy <Dictionary <string, SuggestionResult> > suggestLazy = session
                                                                                .Query <Employee>("Employees_ByFullName")
                                                                                .SuggestUsing(builder => builder.ByField("FullName", "johne"))
                                                                                .ExecuteLazy();

                    Dictionary <string, SuggestionResult> suggest = suggestLazy.Value; // query will be executed here
                    List <string> suggestions = suggest["FullName"].Suggestions;
                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_9
                    Lazy <Dictionary <string, FacetResult> > facetsLazy = session
                                                                          .Query <Camera>("Camera/Costs")
                                                                          .AggregateUsing("facets/CameraFacets")
                                                                          .ExecuteLazy();

                    Dictionary <string, FacetResult> facets = facetsLazy.Value; // query will be executed here
                    FacetResult results = facets["Manufacturer"];
                    #endregion
                }
            }
        }
コード例 #23
0
 public MultiSearchFacet(FacetResult facetResult)
 {
     Value     = facetResult.Value;
     From      = facetResult.From;
     To        = facetResult.To;
     FacetType = facetResult.FacetType;
     if (facetResult.Count.HasValue)
     {
         Count = facetResult.Count.Value;
     }
 }
コード例 #24
0
        public virtual void TestManyFacetsInOneDocument()
        {
            AssumeTrue("default Codec doesn't support huge BinaryDocValues", TestUtil.FieldSupportsHugeBinaryDocValues(FacetsConfig.DEFAULT_INDEX_FIELD_NAME));
            Store.Directory   dir     = NewDirectory();
            Store.Directory   taxoDir = NewDirectory();
            IndexWriterConfig iwc     = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
            RandomIndexWriter writer  = new RandomIndexWriter(Random(), dir, iwc);
            var taxoWriter            = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode_e.CREATE);

            FacetsConfig config = new FacetsConfig();

            config.SetMultiValued("dim", true);

            int numLabels = TestUtil.NextInt(Random(), 40000, 100000);

            Document doc = new Document();

            doc.Add(NewTextField("field", "text", Field.Store.NO));
            for (int i = 0; i < numLabels; i++)
            {
                doc.Add(new FacetField("dim", "" + i));
            }
            writer.AddDocument(config.Build(taxoWriter, doc));

            // NRT open
            IndexSearcher searcher = NewSearcher(writer.Reader);

            // NRT open
            var taxoReader = new DirectoryTaxonomyReader(taxoWriter);

            // Aggregate the facet counts:
            FacetsCollector c = new FacetsCollector();

            // MatchAllDocsQuery is for "browsing" (counts facets
            // for all non-deleted docs in the index); normally
            // you'd use a "normal" query, and use MultiCollector to
            // wrap collecting the "normal" hits and also facets:
            searcher.Search(new MatchAllDocsQuery(), c);
            Facets facets = GetTaxonomyFacetCounts(taxoReader, config, c);

            FacetResult result = facets.GetTopChildren(int.MaxValue, "dim");

            Assert.AreEqual(numLabels, result.LabelValues.Length);
            var allLabels = new HashSet <string>();

            foreach (LabelAndValue labelValue in result.LabelValues)
            {
                allLabels.Add(labelValue.Label);
                Assert.AreEqual(1, (int)labelValue.Value);
            }
            Assert.AreEqual(numLabels, allLabels.Count);

            IOUtils.Close(searcher.IndexReader, taxoWriter, writer, taxoReader, dir, taxoDir);
        }
コード例 #25
0
 private static void AddAggregationValue(AggregationResponse aggregation, FacetResult facetResult, string valueId)
 {
     if (facetResult != null && facetResult.Count > 0)
     {
         var aggregationValue = new AggregationResponseValue
         {
             Id    = valueId,
             Count = facetResult.Count ?? 0,
         };
         aggregation.Values.Add(aggregationValue);
     }
 }
コード例 #26
0
        private static string GetFacetStringValue(FacetResult result)
        {
            if (result.Value is string strVal)
            {
                return(strVal);
            }

            if (result.Value is DateTimeOffset dtoffVal)
            {
                return(dtoffVal.ToString("yyyy-MM-dd"));
            }

            return(result.Value.ToString());
        }
コード例 #27
0
        public static void TestFlexLuceneRAM(string[] args)
        {
            StandardAnalyzer analyzer = new StandardAnalyzer();

            FlexLucene.Store.Directory index = (FlexLucene.Store.Directory) new RAMDirectory();
            config = new IndexWriterConfig((Analyzer)analyzer);
            cnf    = new FacetsConfig();
            cnf.SetIndexFieldName("title", "facet_title");
            cnf.SetIndexFieldName("isbn", "facet_isbn");
            LuceneTest.taxoDir    = (FlexLucene.Store.Directory) new RAMDirectory();
            LuceneTest.taxoWriter = (TaxonomyWriter) new FlexLucene.Facet.Taxonomy.Directory.DirectoryTaxonomyWriter(LuceneTest.taxoDir, IndexWriterConfigOpenMode.CREATE);

            IndexWriter w = new IndexWriter(index, LuceneTest.config);

            addDoc(w, "Lucene in Action", "9900001");
            addDoc(w, "Lucene for Dummies", "9900002");
            addDoc(w, "Lucene for Dummies 2", "9900003");

            w.close();
            String               querystr    = "isbn:99*";
            Query                q           = new QueryParser("title", (Analyzer)analyzer).Parse(querystr);
            int                  hitsPerPage = 10;
            IndexReader          reader      = (IndexReader)DirectoryReader.Open(index);
            IndexSearcher        searcher    = new IndexSearcher(reader);
            TopScoreDocCollector collector   = TopScoreDocCollector.Create(hitsPerPage);

            searcher.Search(q, (Collector)collector);
            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;
            Console.WriteLine("Found " + hits.Length + " hits.");
            for (int i = 0; i < hits.Length; ++i)
            {
                int      docId = hits [i].Doc;
                Document d     = searcher.Doc(docId);
                Console.WriteLine(i + 1 + ". " + d.Get("isbn") + "\t" + d.Get("title"));
            }
            SortedSetDocValuesReaderState state = (SortedSetDocValuesReaderState) new DefaultSortedSetDocValuesReaderState(reader, "facet_isbn");
            FacetsCollector fc = new FacetsCollector();

            FacetsCollector.Search(searcher, q, 10, (Collector)fc);
            Facets      facets = (Facets) new SortedSetDocValuesFacetCounts(state, fc);
            FacetResult result = facets.GetTopChildren(10, "isbn", new String[0]);

            for (int j = 0; j < result.ChildCount; ++j)
            {
                LabelAndValue lv = result.LabelValues [j];
                Console.WriteLine(String.Format("Label={0}, Value={1}", lv.Label, lv.Value));
            }
            reader.close();
        }
コード例 #28
0
        public FacetMappingProfile()
        {
            CreateMap <Aggregation, FacetResult>().IncludeAllDerived();

            CreateMap <Aggregation, FacetResult>().ConvertUsing((request, facet, context) =>
            {
                context.Items.TryGetValue("cultureName", out var cultureNameObj);
                var cultureName    = cultureNameObj as string;
                FacetResult result = request.AggregationType switch
                {
                    "attr" => new TermFacetResult
                    {
                        Terms = request.Items.Select(x => new FacetTerm
                        {
                            Count      = x.Count,
                            IsSelected = x.IsApplied,
                            Term       = x.Value.ToString(),

                            Label = x.Labels?.FirstBestMatchForLanguage(x => x.Language, cultureName)?.Label ?? x.Value.ToString(),
                        })
                                .ToArray(),
                        Name = request.Field
                    },
                    "pricerange" => new RangeFacetResult
                    {
                        Ranges = request.Items.Select(x => new FacetRange
                        {
                            Count       = x.Count,
                            From        = Convert.ToInt64(x.RequestedLowerBound),
                            IncludeFrom = x.IncludeLower,
                            FromStr     = x.RequestedLowerBound,
                            To          = Convert.ToInt64(x.RequestedUpperBound),
                            IncludeTo   = x.IncludeUpper,
                            ToStr       = x.RequestedUpperBound,
                            IsSelected  = x.IsApplied,
                            Label       = x.Value.ToString(),
                        })
                                 .ToArray(),
                        Name = request.Field,
                    },
                    _ => null
                };
                if (result != null)
                {
                    result.Label = request.Labels?.FirstBestMatchForLanguage(x => x.Language, cultureName)?.Label ?? result.Name;
                }
                return(result);
            });
        }
コード例 #29
0
        public async Task ExploreCategory(IDialogContext context, LuisResult result)
        {
            EntityRecommendation categoryEntityRecommendation;

            result.TryFindEntity("category", out categoryEntityRecommendation);
            var category =
                ((Newtonsoft.Json.Linq.JArray)categoryEntityRecommendation?
                 .Resolution["values"])?[0]?.ToString();
            var originalText = result.Query;

            AzureSearchService searchService = new AzureSearchService();

            if (string.IsNullOrWhiteSpace(category))
            {
                FacetResult facetResult = await searchService.FetchFacets();

                if (facetResult.Facets.Category.Length != 0)
                {
                    List <string> categories = new List <string>();
                    foreach (Category searchedCategory in facetResult.Facets.Category)
                    {
                        categories.Add($"{searchedCategory.Value}({ searchedCategory.Count})");
                    }

                    PromptDialog.Choice(context, this.AfterMenuSelection, categories,
                                        "お探しの答えがKBの中にあるか確認しましょう。" +
                                        "どのカテゴリーをご覧になりますか?");
                }
            }
            else
            {
                SearchResult searchResult
                    = await searchService.SearchByCategory(category);

                if (searchResult.Value.Length != 0)
                {
                    await context.PostAsync($"{category} には以下のようなKBが" +
                                            "見つかりました。" +
                                            "**More details** をクリックすると詳細が表示されます。");
                }

                await CardUtil.ShowSearchResults(context, searchResult,
                                                 $"KBから{category} カテゴリーの記事は見つかりませんでした。");

                context.Done <object>(null);
            }
        }
コード例 #30
0
        public override IList <FacetResult> GetAllDims(int topN)
        {
            List <FacetResult> results = new List <FacetResult>();

            foreach (KeyValuePair <string, OrdRange> ent in state.PrefixToOrdRange)
            {
                FacetResult fr = GetDim(ent.Key, ent.Value, topN);
                if (fr != null)
                {
                    results.Add(fr);
                }
            }

            // Sort by highest count:
            results.Sort(new ComparerAnonymousInnerClassHelper(this));
            return(results);
        }