Example #1
0
        public List <SearchResult> Search(string queryString, out int totalHits)
        {
            var l = new List <SearchResult>();

            // Parse the query - assuming it's not a single term but an actual query string
            // Note the QueryParser used is using the same analyzer used for indexing
            var query = queryParser.Parse(queryString);

            var _totalHits = 0;

            // Execute the search with a fresh indexSearcher
            searcherManager.MaybeRefreshBlocking();
            searcherManager.ExecuteSearch(searcher =>
            {
                var topDocs = searcher.Search(query, 10);
                _totalHits  = topDocs.TotalHits;
                foreach (var result in topDocs.ScoreDocs)
                {
                    var doc = searcher.Doc(result.Doc);
                    l.Add(new SearchResult
                    {
                        Name        = doc.GetField("name")?.StringValue,
                        Description = doc.GetField("description")?.StringValue,
                        Url         = doc.GetField("url")?.StringValue,

                        // Results are automatically sorted by relevance
                        Score = result.Score,
                    });
                }
            }, exception => { Console.WriteLine(exception.ToString()); });

            totalHits = _totalHits;
            return(l);
        }
Example #2
0
        public IEnumerable <MenuItem> Search(string queryString, ResultFilter filter = null)
        {
            if (queryString != null)
            {
                queryString = queryString.Trim();
            }
            if (string.IsNullOrEmpty(queryString))
            {
                yield break;
            }
            queryString  = Escape(queryString);
            queryString += "~";

            // FuzzyQuery query = new FuzzyQuery(new Term("joe", queryString), 5);
            // parser.FuzzyMinSim = 10f;
            Query query = parser.Parse(queryString);

            manager.MaybeRefreshBlocking();
            IndexSearcher searcher = manager.Acquire();

            try
            {
                TopDocs documents = searcher.Search(query, (filter ?? ResultFilter.Default).Limit > 0 ? filter.Limit : 1);
                foreach (ScoreDoc scoreDocument in documents.ScoreDocs)
                {
                    Document document = searcher.Doc(scoreDocument.Doc);
                    yield return(items[document.GetField(DESCRIPTION).GetStringValue()]);
                }
            }
            finally
            {
                manager.Release(searcher);
                searcher = null;
            }
        }
 /// <summary>
 /// Reopens the underlying searcher; it's best to "batch
 /// up" many additions/updates, and then call refresh
 /// once in the end.
 /// </summary>
 public virtual void Refresh()
 {
     if (m_searcherMgr == null) // LUCENENET specific -Support for LUCENE-5889.
     {
         throw IllegalStateException.Create("suggester was not built");
     }
     m_searcherMgr.MaybeRefreshBlocking();
 }
Example #4
0
 /// <summary>
 /// Reopens the underlying searcher; it's best to "batch
 /// up" many additions/updates, and then call refresh
 /// once in the end.
 /// </summary>
 public virtual void Refresh()
 {
     if (m_searcherMgr == null)
     {
         throw new InvalidOperationException("suggester was not built");
     }
     m_searcherMgr.MaybeRefreshBlocking();
 }
Example #5
0
        public SearchResults Search(string queryString)
        {
            int resultsPerPage = 10;
            var analyzer       = SetupAnalyzer();
            var queryParser    = SetupQueryParser(analyzer);
            IEnumerable <FieldDefinition> fields = new List <FieldDefinition> {
                new FieldDefinition {
                    Name = "title", isDefault = true
                },
                new FieldDefinition {
                    Name = "description", isDefault = false
                }
            };
            // Query query = BuildQuery(queryString,queryParser); // BuildQuery(queryString, fields); //
            Query query;

            if (queryString.EndsWith('~'))
            {
                query = BuildQuery(queryString, queryParser);
            }
            else
            {
                query = BuildQuery(queryString, fields);
            }

            using (var writer = new IndexWriter(_directory,
                                                new IndexWriterConfig(MATCH_LUCENE_VERSION, analyzer)))
            {
                var searchManager = new SearcherManager(writer, true, null);
                searchManager.MaybeRefreshBlocking();
                IndexSearcher searcher = searchManager.Acquire();

                try
                {
                    TopDocs topDocs = searcher.Search(query, resultsPerPage);
                    return(CompileResults(searcher, topDocs));
                }
                finally
                {
                    searchManager?.Release(searcher);
                    searchManager?.Dispose();
                    searcher = null;
                    analyzer?.Dispose();
                    ReleaseWriteLock();
                }
            }
        }
        public SearchResults Search(string queryString)
        {
            int   resultsPerPage = 10;
            Query query          = BuildQuery(queryString);

            searchManager.MaybeRefreshBlocking();
            IndexSearcher searcher = searchManager.Acquire();

            try
            {
                TopDocs topdDocs = searcher.Search(query, resultsPerPage);
                return(CompileResults(searcher, topdDocs));
            }
            finally
            {
                searchManager.Release(searcher);
                searcher = null;
            }
        }
        public async Task <IEnumerable <SearchResult> > Search(IDictionary <string, string> matches)
        {
            var results = new List <SearchResult>();

            using (Directory directory = FSDirectory.Open(this._directory))
            {
                SearcherManager searchManager = new SearcherManager(directory, null);


                searchManager.MaybeRefreshBlocking();
                IndexSearcher indexSearcher = searchManager.Acquire();

                var booleanQuery = new BooleanQuery();

                foreach (var match in matches)
                {
                    booleanQuery.Add(new TermQuery(new Term(match.Key, match.Value)), Occur.MUST);
                }

                var hits   = indexSearcher.Search(booleanQuery, int.MaxValue);
                var scored = hits.ScoreDocs;

                foreach (var item in scored)
                {
                    Document doc = indexSearcher.Doc(item.Doc);

                    string url     = doc.Get("Url");
                    var    content = await this._contentService.GetContent(url);

                    results.Add(new SearchResult
                    {
                        Url         = url,
                        PreviewText = doc.Get("Body"),
                        Score       = item.Score,
                        Content     = content
                    });
                }
            }

            return(results);
        }
Example #8
0
        public SearchResults Search(string queryString)
        {
            int resultsPerPage            = 10;
            List <FieldDefinition> fields = new List <FieldDefinition> {
                new FieldDefinition {
                    Name = "title", IsDefault = true
                },
                new FieldDefinition {
                    Name = "rating"
                },
                new FieldDefinition {
                    Name = "description"
                }
            };

            Query query = BuildQuery(queryString, fields);

            searcherManager.MaybeRefreshBlocking();
            IndexSearcher searcher = searcherManager.Acquire();

            try {
                TopDocs topDocs = searcher.Search(query, resultsPerPage);
                if (topDocs.TotalHits < 1)
                {
                    Console.WriteLine("No result found with TermQuery, Calling Prefix Query");
                    query   = BuildQuery(queryString, fields, true);
                    topDocs = searcher.Search(query, resultsPerPage);
                }
                if (topDocs.TotalHits < 1)
                {
                    Console.WriteLine("No result found with PrefixQuery, Calling Fuzzy Query");
                    query   = BuildQuery(queryString, fields, true, true);
                    topDocs = searcher.Search(query, resultsPerPage);
                }
                return(CompileResults(searcher, topDocs));
            }
            finally {
                searcherManager.Release(searcher);
                searcher = null;
            }
        }
        /// <summary>
        /// Performs a search to find information across the whole documentation.
        /// </summary>
        /// <param name="queryString"> The query of the search.</param>
        /// <returns>A list which contains all the pages which match to the query.</returns>
        public string Search(string queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
            {
                return(null);
            }

            var listSearchResult = new List <Page>();

            // Parse the query - assuming it's not a single term but an actual query string
            var query = QueryParser.Parse(queryString);

            // Execute the search with a fresh indexSearcher
            SearcherManager.MaybeRefreshBlocking();
            SearcherManager.ExecuteSearch(searcher =>
            {
                var topDocs = searcher.Search(query, 10);
                foreach (var result in topDocs.ScoreDocs)
                {
                    var doc = searcher.Doc(result.Doc);
                    listSearchResult.Add(new Page
                    {
                        Name = doc.GetField("name")?.StringValue,
                        Path = doc.GetField("path")?.StringValue,
                    });
                }
            }, exception => { Console.WriteLine(exception.ToString()); });

            var listPagesContentResult       = this.SearchInPagesContent(queryString);
            var listPagesContentResultUpdate = new List <Page>();

            foreach (var result in listPagesContentResult)
            {
                if (!listSearchResult.Exists(x => x.Path == result.Path))
                {
                    listPagesContentResultUpdate.Add(result);
                }
            }

            return(this.markdownToHtml.CreateHtmlPageFromResults(queryString, listSearchResult, listPagesContentResultUpdate, this.PathIndexDirectory));
        }
 /// <summary>
 /// Reopens the underlying searcher; it's best to "batch
 /// up" many additions/updates, and then call refresh
 /// once in the end.
 /// </summary>
 public virtual void Refresh()
 {
     m_searcherMgr.MaybeRefreshBlocking();
 }
        public async Task <IEnumerable <SearchResult> > Search(string searchTerm)
        {
            var results = new List <SearchResult>();

            var queryParser = SetupQueryParser(SetupAnalyzer());
            var query       = queryParser.Parse(searchTerm);

            ScoreDoc[] scored;

            //using (Directory directory = FSDirectory.Open(this._directory))
            //{
            //    using (var writer = new IndexWriter(directory,
            //       new IndexWriterConfig(LuceneVersion.LUCENE_CURRENT, SetupAnalyzer())))
            //    {
            //        using(var reader = writer.GetReader(false))
            //        {
            //            for (int i = 0; i < reader.MaxDoc; i++)
            //            {


            //                Document doc = reader.Document(i);
            //                string type = doc.GetField("Type").GetStringValue();

            //                if(type == "content")
            //                {

            //                }
            //                // do something with docId here...
            //            }
            //        }
            //    }
            //}

            using (Directory directory = FSDirectory.Open(this._directory))
            {
                SearcherManager searchManager = new SearcherManager(directory, null);

                searchManager.MaybeRefreshBlocking();
                IndexSearcher indexSearcher = searchManager.Acquire();

                TopDocs hits = indexSearcher.Search(query, int.MaxValue);

                scored = hits.ScoreDocs;

                foreach (var item in scored)
                {
                    Document doc         = indexSearcher.Doc(item.Doc);
                    var      previewText = GeneratePreviewText(query, doc.Get("Body"));
                    string   url         = doc.Get("Url");
                    var      content     = await this._contentService.GetContent(url);

                    results.Add(new SearchResult
                    {
                        Url         = url,
                        PreviewText = doc.Get("Body"),
                        Score       = item.Score,
                        Content     = content
                    });
                }
            }

            return(results);
        }
        public virtual void TestReferenceDecrementIllegally([ValueSource(typeof(ConcurrentMergeSchedulers), "Values")]IConcurrentMergeScheduler scheduler)
        {
            Directory dir = NewDirectory();
            var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
                            .SetMergeScheduler(scheduler);
            IndexWriter writer = new IndexWriter(dir, config);
            SearcherManager sm = new SearcherManager(writer, false, new SearcherFactory());
            writer.AddDocument(new Document());
            writer.Commit();
            sm.MaybeRefreshBlocking();

            IndexSearcher acquire = sm.Acquire();
            IndexSearcher acquire2 = sm.Acquire();
            sm.Release(acquire);
            sm.Release(acquire2);

            acquire = sm.Acquire();
            acquire.IndexReader.DecRef();
            sm.Release(acquire);

            Assert.Throws<InvalidOperationException>(() => sm.Acquire(), "acquire should have thrown an InvalidOperationException since we modified the refCount outside of the manager");

            // sm.Dispose(); -- already closed
            writer.Dispose();
            dir.Dispose();
        }
 public virtual void TestListenerCalled()
 {
     Directory dir = NewDirectory();
     IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
     AtomicBoolean afterRefreshCalled = new AtomicBoolean(false);
     SearcherManager sm = new SearcherManager(iw, false, new SearcherFactory());
     sm.AddListener(new RefreshListenerAnonymousInnerClassHelper(this, afterRefreshCalled));
     iw.AddDocument(new Document());
     iw.Commit();
     Assert.IsFalse(afterRefreshCalled.Get());
     sm.MaybeRefreshBlocking();
     Assert.IsTrue(afterRefreshCalled.Get());
     sm.Dispose();
     iw.Dispose();
     dir.Dispose();
 }
        public virtual void TestReferenceDecrementIllegally()
        {
            Directory dir = NewDirectory();
            IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergeScheduler(new ConcurrentMergeScheduler()));
            SearcherManager sm = new SearcherManager(writer, false, new SearcherFactory());
            writer.AddDocument(new Document());
            writer.Commit();
            sm.MaybeRefreshBlocking();

            IndexSearcher acquire = sm.Acquire();
            IndexSearcher acquire2 = sm.Acquire();
            sm.Release(acquire);
            sm.Release(acquire2);

            acquire = sm.Acquire();
            acquire.IndexReader.DecRef();
            sm.Release(acquire);
            try
            {
                sm.Acquire();
                Assert.Fail("acquire should have thrown an InvalidOperationException since we modified the refCount outside of the manager");
            }
            catch (InvalidOperationException ex)
            {
                //
            }

            // sm.Dispose(); -- already closed
            writer.Dispose();
            dir.Dispose();
        }