当前位置: 首页>>代码示例>>C#>>正文


C# Search.IndexSearcher类代码示例

本文整理汇总了C#中Lucene.Net.Search.IndexSearcher的典型用法代码示例。如果您正苦于以下问题:C# IndexSearcher类的具体用法?C# IndexSearcher怎么用?C# IndexSearcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IndexSearcher类属于Lucene.Net.Search命名空间,在下文中一共展示了IndexSearcher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Search

        public ActionResult Search(string query)
        {
            ViewData["Message"] = "query : " + query;

            var searcher = new IndexSearcher(
                new Lucene.Net.Store.SimpleFSDirectory(new DirectoryInfo(Configuration.IndexDirectory)),
                readOnly: true);

            var fieldsToSearchIn = new[] {Configuration.Fields.Name, Configuration.Fields.Description};
            var queryanalizer = new MultiFieldQueryParser(Version.LUCENE_CURRENT,
                                                          fieldsToSearchIn,
                                                          new BrazilianAnalyzer());

            var numberOfResults = 10;
            var top10Results = searcher.Search(queryanalizer.Parse(query), numberOfResults);
            var docs = new List<DocumentViewModel>();
            foreach (var scoreDoc in top10Results.scoreDocs)
            {
                var document = searcher.Doc(scoreDoc.doc);
                var name = document.GetField(Configuration.Fields.Name).StringValue();
                var description = document.GetField(Configuration.Fields.Description).StringValue();
                var link = document.GetField(Configuration.Fields.Link).StringValue();
                docs.Add(new DocumentViewModel(name, description, link));
            }
            return View(new SearchViewModel(docs));
        }
开发者ID:brunomlopes,项目名称:techdays2010pt-lucene,代码行数:26,代码来源:HomeController.cs

示例2: TestNullOrSubScorer

		public virtual void  TestNullOrSubScorer()
		{
			Directory dir = new MockRAMDirectory();
			IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
			Document doc = new Document();
			doc.Add(new Field("field", "a b c d", Field.Store.NO, Field.Index.ANALYZED));
			w.AddDocument(doc);
			IndexReader r = w.GetReader();
			IndexSearcher s = new IndexSearcher(r);
			BooleanQuery q = new BooleanQuery();
			q.Add(new TermQuery(new Term("field", "a")), BooleanClause.Occur.SHOULD);
			
			// PhraseQuery w/ no terms added returns a null scorer
			PhraseQuery pq = new PhraseQuery();
			q.Add(pq, BooleanClause.Occur.SHOULD);
			Assert.AreEqual(1, s.Search(q, 10).TotalHits);
			
			// A required clause which returns null scorer should return null scorer to
			// IndexSearcher.
			q = new BooleanQuery();
			pq = new PhraseQuery();
			q.Add(new TermQuery(new Term("field", "a")), BooleanClause.Occur.SHOULD);
			q.Add(pq, BooleanClause.Occur.MUST);
			Assert.AreEqual(0, s.Search(q, 10).TotalHits);
			
			DisjunctionMaxQuery dmq = new DisjunctionMaxQuery(1.0f);
			dmq.Add(new TermQuery(new Term("field", "a")));
			dmq.Add(pq);
			Assert.AreEqual(1, s.Search(dmq, 10).TotalHits);
			
			r.Close();
			w.Close();
			dir.Close();
		}
开发者ID:Mpdreamz,项目名称:lucene.net,代码行数:34,代码来源:TestBooleanQuery.cs

示例3: TestBasic

		public virtual void  TestBasic()
		{
			Directory dir = new RAMDirectory();
			IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
			Document doc = new Document();
			doc.Add(new Field("field", "value", Field.Store.NO, Field.Index.ANALYZED));
			writer.AddDocument(doc);
			writer.Close();
			
			TermQuery termQuery = new TermQuery(new Term("field", "value"));
			
			// should not throw exception with primitive query
			QueryWrapperFilter qwf = new QueryWrapperFilter(termQuery);
			
			IndexSearcher searcher = new IndexSearcher(dir, true);
			TopDocs hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
			Assert.AreEqual(1, hits.totalHits);
			
			// should not throw exception with complex primitive query
			BooleanQuery booleanQuery = new BooleanQuery();
			booleanQuery.Add(termQuery, Occur.MUST);
			booleanQuery.Add(new TermQuery(new Term("field", "missing")), Occur.MUST_NOT);
			qwf = new QueryWrapperFilter(termQuery);
			
			hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
			Assert.AreEqual(1, hits.totalHits);
			
			// should not throw exception with non primitive Query (doesn't implement
			// Query#createWeight)
			qwf = new QueryWrapperFilter(new FuzzyQuery(new Term("field", "valu")));
			
			hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
			Assert.AreEqual(1, hits.totalHits);
		}
开发者ID:Rationalle,项目名称:ravendb,代码行数:34,代码来源:TestQueryWrapperFilter.cs

示例4: Find

        public SearchResults Find(string terms)
        {
            Directory directory = FSDirectory.GetDirectory("./index",false);
            // Now search the index:
            var isearcher = new IndexSearcher(directory);
            // Parse a simple query that searches for "text":
            //Query query = QueryParser.Parse("text", "fieldname", analyzer);
            var qp = new QueryParser("description", _analyzer);
            Query query = qp.Parse(terms);

            Hits hits = isearcher.Search(query);

            var sr = new SearchResults();

            // Iterate through the results:
            for (int i = 0; i < hits.Length(); i++)
            {
                Document hitDoc = hits.Doc(i);

                sr.Add(new Result() { Name = hitDoc.Get("name"), Description = hitDoc.Get("description") });
            }
            isearcher.Close();
            directory.Close();

            return sr;
        }
开发者ID:drusellers,项目名称:biblioteca,代码行数:26,代码来源:LuceneSearch.cs

示例5: Search

        public Task<SearchResultCollection> Search(string search)
        {
            return System.Threading.Tasks.Task.Run(() =>
            {
                var src = new SearchResultCollection();
                if (string.IsNullOrWhiteSpace(search)) return src;
                try
                {

                                                       
                    var parser = new QueryParser(Version.LUCENE_30,"All", analyzer);
                    Query q = new TermQuery(new Term("All", search));
                                                           
                    using (var indexSearcher = new IndexSearcher(directory, true))
                    {
                        Query query = parser.Parse(search);
                        TopDocs result = indexSearcher.Search(query, 50);
                        foreach (ScoreDoc h in result.ScoreDocs)
                        {
                            Document doc = indexSearcher.Doc(h.Doc);
                            string id = doc.Get("id");
                            BaseContent value;
                            if (LookupTable.TryGetValue(id, out value)) src.Add(new SearchResult {Relevance = h.Score, Content = value});
                        }
                    }
                }
                catch (Exception e)
                {

                    Logger.Log("DataServer","Error lucene search",e.Message,Logger.Level.Error);
                }
                return src;
            });
        }
开发者ID:TNOCS,项目名称:csTouch,代码行数:34,代码来源:LuceneSearch.cs

示例6: TestQuery

		public virtual void  TestQuery()
		{
			RAMDirectory dir = new RAMDirectory();
			IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(), true);
			AddDoc("one", iw);
			AddDoc("two", iw);
			AddDoc("three four", iw);
			iw.Close();
			
			IndexSearcher is_Renamed = new IndexSearcher(dir);
			Hits hits = is_Renamed.Search(new MatchAllDocsQuery());
			Assert.AreEqual(3, hits.Length());
			
			// some artificial queries to trigger the use of skipTo():
			
			BooleanQuery bq = new BooleanQuery();
			bq.Add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
			bq.Add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
			hits = is_Renamed.Search(bq);
			Assert.AreEqual(3, hits.Length());
			
			bq = new BooleanQuery();
			bq.Add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
			bq.Add(new TermQuery(new Term("key", "three")), BooleanClause.Occur.MUST);
			hits = is_Renamed.Search(bq);
			Assert.AreEqual(1, hits.Length());
			
			// delete a document:
			is_Renamed.GetIndexReader().DeleteDocument(0);
			hits = is_Renamed.Search(new MatchAllDocsQuery());
			Assert.AreEqual(2, hits.Length());
			
			is_Renamed.Close();
		}
开发者ID:vikasraz,项目名称:indexsearchutils,代码行数:34,代码来源:TestMatchAllDocsQuery.cs

示例7: SetUp

 public override void  SetUp()
 {
     base.SetUp();
     IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
     //writer.setUseCompoundFile(true);
     //writer.infoStream = System.out;
     for (int i = 0; i < 1000; i++)
     {
         Document doc = new Document();
         Field.TermVector termVector;
         int mod3 = i % 3;
         int mod2 = i % 2;
         if (mod2 == 0 && mod3 == 0)
         {
             termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
         }
         else if (mod2 == 0)
         {
             termVector = Field.TermVector.WITH_POSITIONS;
         }
         else if (mod3 == 0)
         {
             termVector = Field.TermVector.WITH_OFFSETS;
         }
         else
         {
             termVector = Field.TermVector.YES;
         }
         doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED, termVector));
         writer.AddDocument(doc);
     }
     writer.Close();
     searcher = new IndexSearcher(directory, true);
 }
开发者ID:Nangal,项目名称:lucene.net,代码行数:34,代码来源:TestTermVectors.cs

示例8: Search

        public ProjectData[] Search(string searchTerm)
        {
            IndexSearcher searcher = new IndexSearcher(luceneIndexDirectory);
            IntegralCollector searcherCollector = new IntegralCollector();
            // Setup the fields to search through
            string[] searchfields = new string[] { "name", "vessel" };

            // Build our booleanquery that will be a combination of all the queries for each individual search term
            var finalQuery = new BooleanQuery();
            var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, searchfields, analyzer);

            // Split the search string into separate search terms by word
            string[] terms = searchTerm.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string term in terms)
                finalQuery.Add(parser.Parse(term.Replace("~", "") + "~"),Occur.SHOULD);

            searcher.Search(finalQuery, searcherCollector);
            var results = new ProjectData[searcherCollector.Docs.Count];
            for (int i = 0; i < searcherCollector.Docs.Count; i++)
            {
                var doc = searcher.Doc(searcherCollector.Docs[i]);
                results[i] = new ProjectData(doc.Get("name"), doc.Get("vessel"));
            }
            return results;
        }
开发者ID:trymnilsen,项目名称:AegirServer,代码行数:25,代码来源:LuceneService.cs

示例9: Search

        public ISearchResult Search(string query)
        {
            var timer = new Stopwatch();
            timer.Start();

            var directory = FSDirectory.Open(new DirectoryInfo(path));
            var analyzer = new StandardAnalyzer(Version.LUCENE_29);
            var searcher = new IndexSearcher(directory, true);

            var queryParser = new QueryParser(Version.LUCENE_29, "text", analyzer);
            var result = searcher.Search(queryParser.Parse(query), 20);

            var docs = (from scoreDoc in result.scoreDocs
                        let doc = searcher.Doc(scoreDoc.doc)
                        let fields = new Dictionary<string, string> { { "title", doc.Get("title") }, { "text", doc.Get("text") } }
                        select new LuceneDocument { Id = scoreDoc.doc.ToString(), Fields = fields }).ToList();

            var ret = new SearchResult { Query = query, Total = result.totalHits, Documents = docs, Source = Name };

            searcher.Close();
            directory.Close();

            timer.Stop();
            ret.Duration = (decimal) timer.Elapsed.TotalSeconds;

            return ret;
        }
开发者ID:billings-dot-net-users-group,项目名称:search-demo,代码行数:27,代码来源:LuceneIndex.cs

示例10: MrsJones

        public void MrsJones()
        {
            using (var dir = new RAMDirectory())
            using (var analyzer = new LowerCaseKeywordAnalyzer())
            {
                using (var writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
                {
                    var document = new Lucene.Net.Documents.Document();
                    document.Add(new Field("Name", "MRS. SHABA", Field.Store.NO, Field.Index.ANALYZED_NO_NORMS));
                    writer.AddDocument(document);
                }

                var searcher = new IndexSearcher(dir, true);

                var termEnum = searcher.IndexReader.Terms();
                while (termEnum.Next())
                {
                    var buffer = termEnum.Term.Text;
                    Console.WriteLine(buffer);
                }

                var queryParser = new RangeQueryParser(Version.LUCENE_29, "", analyzer);
                var query = queryParser.Parse("Name:\"MRS. S*\"");
                Console.WriteLine(query);
                var result = searcher.Search(query, 10);

                Assert.NotEqual(0, result.TotalHits);
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:29,代码来源:LuceneIndexing.cs

示例11: ResetSearcher

            void ResetSearcher()
            {
                var start = DateTime.Now;
                searcherLock.EnterWriteLock();
                try
                {
                    if (lastReset > start) return;

                    lastReset = DateTime.Now;
                    var newSearcher = new IndexSearcher(
                        MMapDirectory.GetDirectory(this.path, false)
                    );

                    var oldSearcher = this.searcher;
                    this.searcher = newSearcher;

                    if (oldSearcher != null)
                    {
                        oldSearcher.Close();
                    }
                }
                finally
                {
                    searcherLock.ExitWriteLock();
                }
            }
开发者ID:mrkurt,项目名称:mubble-old,代码行数:26,代码来源:Index.Searcher.cs

示例12: getNotesMatchingTitle

        public ArrayList getNotesMatchingTitle(string search)
        {
            ArrayList snotes = new ArrayList ();

            try {
                QueryParser parser = new QueryParser ("title", analyzer);

                string lucsearch = search + "*^4" + " content:" + search + "*";

                Query query = parser.Parse (lucsearch);
                IndexSearcher searcher = new IndexSearcher (lucIdx);
                Hits hits = searcher.Search (query);

                int results = hits.Length ();
                Console.WriteLine ("Found {0} results", results);
                for (int i = 0; i < results; i++) {
                    Document doc = hits.Doc (i);
                    //float score = hits.Score (i);
                    snotes.Add (new Note (doc.Get ("title"), doc.Get ("lastmod")));
                }
            } catch (Exception e) {
                Console.WriteLine ("ERROR Search: " + e.Message);
            }

            return snotes;
        }
开发者ID:mzehrer,项目名称:monovel,代码行数:26,代码来源:FilesystemNotesStore.cs

示例13: Initialize_Indexes_All_Nodes

        public void Initialize_Indexes_All_Nodes()
        {
            string elementIdForTestingSearch = _deepNodeFinder.GetNodesForIndexing()[0].Id;
            int expectedNumNodes = _deepNodeFinder.GetNodesForIndexing().Length;

            Assert.AreEqual("usfr-pte_NetCashFlowsProvidedUsedOperatingActivitiesDirectAbstract", elementIdForTestingSearch,
                            "TEST SANITY: element id for test search");
            Assert.AreEqual(1595, expectedNumNodes, "TEST SANITY: Number of nodes in found in the test taxonomy");

            IndexReader indexReader = IndexReader.Open(_indexMgr.LuceneDirectory_ForTesting);

            Assert.AreEqual(expectedNumNodes, indexReader.NumDocs(),
                            "An incorrect number of documents were found in the Lucene directory after initialization");

            IndexSearcher searcher = new IndexSearcher(_indexMgr.LuceneDirectory_ForTesting);
            try
            {
                Hits results =
                    searcher.Search(new TermQuery(new Term(LuceneNodeIndexer.ELEMENTID_FOR_DELETING_FIELD, elementIdForTestingSearch)));

                Assert.AreEqual(1, results.Length(), "Search results should only have 1 hit");
                Assert.AreEqual(elementIdForTestingSearch, results.Doc(0).Get(LuceneNodeIndexer.ELEMENTID_FIELD),
                                "Search results yielded the wrong element!");
            }
            finally
            {
                searcher.Close();
            }
        }
开发者ID:plamikcho,项目名称:xbrlpoc,代码行数:29,代码来源:TestLuceneIndexMgr.cs

示例14: searchLucene

        public Data searchLucene(Data data)
        {
            Search_gl search = new Search_gl();
            List<string> item = new List<string>();
            Lucene.Net.Store.Directory directory = FSDirectory.Open(new DirectoryInfo(Environment.CurrentDirectory + "\\LuceneIndex"));
            var analyzer = new StandardAnalyzer(Version.LUCENE_29);

            IndexReader reader = IndexReader.Open(directory, true);
            IndexSearcher searcher = new IndexSearcher(reader);

            //QueryParser queryParser = new QueryParser(Version.LUCENE_29, "summary", analyzer);  //search for single field
            MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[] {"name", "summary"}, analyzer);  //search for multifield
            Query query = parser.Parse((data.getString("search")) + "*"); //cant search blank text with wildcard as first character

            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
            searcher.Search(query, collector);
            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;
            int count = hits.Length;

            for (int i = 0; i < count; i++)
            {
                int docId = hits[i].doc;
                float score = hits[i].score;

                Document doc = searcher.Doc(docId);

                string id = doc.Get("id");
                item.Add(id);
            }
            Data list = search.search(data, item.ToArray());
            reader.Close();
            searcher.Close();

            return list;
        }
开发者ID:hyori7,项目名称:WebDirectory,代码行数:35,代码来源:Lucene_gl.cs

示例15: BroadcastNodeReopen

        // Called by one node once it has reopened, to notify all
        // other nodes.  this is just a mock (since it goes and
        // directly updates all other nodes, in RAM)... in a real
        // env this would hit the wire, sending version &
        // collection stats to all other nodes:
        internal virtual void BroadcastNodeReopen(int nodeID, long version, IndexSearcher newSearcher)
        {
            if (VERBOSE)
            {
                Console.WriteLine("REOPEN: nodeID=" + nodeID + " version=" + version + " maxDoc=" + newSearcher.IndexReader.MaxDoc);
            }

            // Broadcast new collection stats for this node to all
            // other nodes:
            foreach (string field in FieldsToShare)
            {
                CollectionStatistics stats = newSearcher.CollectionStatistics(field);
                foreach (NodeState node in Nodes)
                {
                    // Don't put my own collection stats into the cache;
                    // we pull locally:
                    if (node.MyNodeID != nodeID)
                    {
                        node.CollectionStatsCache[new FieldAndShardVersion(nodeID, version, field)] = stats;
                    }
                }
            }
            foreach (NodeState node in Nodes)
            {
                node.UpdateNodeVersion(nodeID, version);
            }
        }
开发者ID:Cefa68000,项目名称:lucenenet,代码行数:32,代码来源:ShardSearchingTestBase.cs


注:本文中的Lucene.Net.Search.IndexSearcher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。