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


C# IndexSearcher.GetIndexReader方法代码示例

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


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

示例1: MrsJones

		public void MrsJones()
		{
			var dir = new RAMDirectory();
			var analyzer = new LowerCaseKeywordAnalyzer();
			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);

			writer.Close(true);
			

			var searcher = new IndexSearcher(dir, true);

			var termEnum = searcher.GetIndexReader().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:jtmueller,项目名称:ravendb,代码行数:28,代码来源:LuceneIndexing.cs

示例2: 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

示例3: GetHighlight

		public string GetHighlight(string value, IndexSearcher searcher, string highlightField, Query luceneQuery)
		{
			var scorer = new QueryScorer(luceneQuery.Rewrite(searcher.GetIndexReader()));
			var highlighter = new Highlighter(HighlightFormatter, scorer);

			var tokenStream = HighlightAnalyzer.TokenStream(highlightField, new StringReader(value));
			return highlighter.GetBestFragments(tokenStream, value, MaxNumHighlights, Separator);
		}
开发者ID:joosthollander,项目名称:Macaw.Umbraco.Foundation,代码行数:8,代码来源:LuceneHighlightHelper.cs

示例4: TestQuery

		public virtual void  TestQuery()
		{
			
			RAMDirectory dir = new RAMDirectory();
			IndexWriter iw = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
			iw.SetMaxBufferedDocs(2); // force multi-segment
			AddDoc("one", iw, 1f);
			AddDoc("two", iw, 20f);
			AddDoc("three four", iw, 300f);
			iw.Close();
			
			IndexReader ir = IndexReader.Open(dir);
			IndexSearcher is_Renamed = new IndexSearcher(ir);
			ScoreDoc[] hits;
			
			// assert with norms scoring turned off
			
			hits = is_Renamed.Search(new MatchAllDocsQuery(), null, 1000).ScoreDocs;
			Assert.AreEqual(3, hits.Length);
			Assert.AreEqual(ir.Document(hits[0].Doc).Get("key"), "one");
			Assert.AreEqual(ir.Document(hits[1].Doc).Get("key"), "two");
			Assert.AreEqual(ir.Document(hits[2].Doc).Get("key"), "three four");
			
			// assert with norms scoring turned on
			
			MatchAllDocsQuery normsQuery = new MatchAllDocsQuery("key");
			hits = is_Renamed.Search(normsQuery, null, 1000).ScoreDocs;
			Assert.AreEqual(3, hits.Length);
			
			Assert.AreEqual(ir.Document(hits[0].Doc).Get("key"), "three four");
			Assert.AreEqual(ir.Document(hits[1].Doc).Get("key"), "two");
			Assert.AreEqual(ir.Document(hits[2].Doc).Get("key"), "one");
			
			// change norm & retest
			ir.SetNorm(0, "key", 400f);
			normsQuery = new MatchAllDocsQuery("key");
			hits = is_Renamed.Search(normsQuery, null, 1000).ScoreDocs;
			Assert.AreEqual(3, hits.Length);
			
			Assert.AreEqual(ir.Document(hits[0].Doc).Get("key"), "one");
			Assert.AreEqual(ir.Document(hits[1].Doc).Get("key"), "three four");
			Assert.AreEqual(ir.Document(hits[2].Doc).Get("key"), "two");
			
			// 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, null, 1000).ScoreDocs;
			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, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			// delete a document:
			is_Renamed.GetIndexReader().DeleteDocument(0);
			hits = is_Renamed.Search(new MatchAllDocsQuery(), null, 1000).ScoreDocs;
			Assert.AreEqual(2, hits.Length);
			
			// test parsable toString()
			QueryParser qp = new QueryParser("key", analyzer);
			hits = is_Renamed.Search(qp.Parse(new MatchAllDocsQuery().ToString()), null, 1000).ScoreDocs;
			Assert.AreEqual(2, hits.Length);
			
			// test parsable toString() with non default boost
			Query maq = new MatchAllDocsQuery();
			maq.SetBoost(2.3f);
			Query pq = qp.Parse(maq.ToString());
			hits = is_Renamed.Search(pq, null, 1000).ScoreDocs;
			Assert.AreEqual(2, hits.Length);
			
			is_Renamed.Close();
			ir.Close();
			dir.Close();
		}
开发者ID:kstenson,项目名称:NHibernate.Search,代码行数:78,代码来源:TestMatchAllDocsQuery.cs

示例5: CheckFirstSkipTo

		// check that first skip on just created scorers always goes to the right doc
		private static void  CheckFirstSkipTo(Query q, IndexSearcher s)
		{
			//System.out.println("checkFirstSkipTo: "+q);
			float maxDiff = 1e-5f;
			int[] lastDoc = new int[]{- 1};
			s.Search(q, new AnonymousClassHitCollector1(lastDoc, q, s, maxDiff));
			Weight w = q.Weight(s);
			Scorer scorer = w.Scorer(s.GetIndexReader());
			bool more = scorer.SkipTo(lastDoc[0] + 1);
			if (more)
				Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.Doc());
		}
开发者ID:vikasraz,项目名称:indexsearchutils,代码行数:13,代码来源:QueryUtils.cs

示例6: CheckSkipTo

		/// <summary>alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc
		/// and ensure a hitcollector receives same docs and scores
		/// </summary>
		public static void  CheckSkipTo(Query q, IndexSearcher s)
		{
			//System.out.println("Checking "+q);
			
			if (BooleanQuery.GetAllowDocsOutOfOrder())
				return ; // in this case order of skipTo() might differ from that of next().
			
			int skip_op = 0;
			int next_op = 1;
			int[][] orders = new int[][]{new int[]{next_op}, new int[]{skip_op}, new int[]{skip_op, next_op}, new int[]{next_op, skip_op}, new int[]{skip_op, skip_op, next_op, next_op}, new int[]{next_op, next_op, skip_op, skip_op}, new int[]{skip_op, skip_op, skip_op, next_op, next_op}};
			for (int k = 0; k < orders.Length; k++)
			{
				int[] order = orders[k];
				//System.out.print("Order:");for (int i = 0; i < order.length; i++) System.out.print(order[i]==skip_op ? " skip()":" next()"); System.out.println();
				int[] opidx = new int[]{0};
				
				Weight w = q.Weight(s);
				Scorer scorer = w.Scorer(s.GetIndexReader());
				
				// FUTURE: ensure scorer.doc()==-1
				
				int[] sdoc = new int[]{- 1};
				float maxDiff = 1e-5f;
				s.Search(q, new AnonymousClassHitCollector(order, opidx, skip_op, scorer, sdoc, maxDiff, q, s));
				
				// make sure next call to scorer is false.
				int op = order[(opidx[0]++) % order.Length];
				//System.out.println(op==skip_op ? "last: skip()":"last: next()");
				bool more = op == skip_op?scorer.SkipTo(sdoc[0] + 1):scorer.Next();
				Assert.IsFalse(more);
			}
		}
开发者ID:vikasraz,项目名称:indexsearchutils,代码行数:35,代码来源:QueryUtils.cs

示例7: VerifyResults

		// verify results are as expected.
		private void  VerifyResults(float boost, IndexSearcher s, System.Collections.Hashtable h1, System.Collections.Hashtable h2customNeutral, System.Collections.Hashtable h3CustomMul, System.Collections.Hashtable h4CustomAdd, System.Collections.Hashtable h5CustomMulAdd, Query q1, Query q2, Query q3, Query q4, Query q5)
		{
			
			// verify numbers of matches
			Log("#hits = " + h1.Count);
			Assert.AreEqual(h1.Count, h2customNeutral.Count, "queries should have same #hits");
			Assert.AreEqual(h1.Count, h3CustomMul.Count, "queries should have same #hits");
			Assert.AreEqual(h1.Count, h4CustomAdd.Count, "queries should have same #hits");
			Assert.AreEqual(h1.Count, h5CustomMulAdd.Count, "queries should have same #hits");
			
			// verify scores ratios
			for (System.Collections.IEnumerator it = h1.Keys.GetEnumerator(); it.MoveNext(); )
			{
				System.Int32 x = (System.Int32) it.Current;
				
				int doc = x;
				Log("doc = " + doc);
				
				float fieldScore = ExpectedFieldScore(s.GetIndexReader().Document(doc).Get(ID_FIELD));
				Log("fieldScore = " + fieldScore);
				Assert.IsTrue(fieldScore > 0, "fieldScore should not be 0");
				
				float score1 = (float) ((System.Single) h1[x]);
				LogResult("score1=", s, q1, doc, score1);
				
				float score2 = (float) ((System.Single) h2customNeutral[x]);
				LogResult("score2=", s, q2, doc, score2);
				Assert.AreEqual(boost * score1, score2, TEST_SCORE_TOLERANCE_DELTA, "same score (just boosted) for neutral");
				
				float score3 = (float) ((System.Single) h3CustomMul[x]);
				LogResult("score3=", s, q3, doc, score3);
				Assert.AreEqual(boost * fieldScore * score1, score3, TEST_SCORE_TOLERANCE_DELTA, "new score for custom mul");
				
				float score4 = (float) ((System.Single) h4CustomAdd[x]);
				LogResult("score4=", s, q4, doc, score4);
				Assert.AreEqual(boost * (fieldScore + score1), score4, TEST_SCORE_TOLERANCE_DELTA, "new score for custom add");
				
				float score5 = (float) ((System.Single) h5CustomMulAdd[x]);
				LogResult("score5=", s, q5, doc, score5);
				Assert.AreEqual(boost * fieldScore * (score1 + fieldScore), score5, TEST_SCORE_TOLERANCE_DELTA, "new score for custom mul add");
			}
		}
开发者ID:kstenson,项目名称:NHibernate.Search,代码行数:43,代码来源:TestCustomScoreQuery.cs

示例8: ValidateSearcher

        private void ValidateSearcher(bool forceReopen)
        {
            EnsureIndex();

            if (!forceReopen)
            {
                if (_searcher == null)
                {
                    lock (Locker)
                    {
                        //double check
                        if (_searcher == null)
                        {

                            try
                            {
                                _searcher = new IndexSearcher(GetLuceneDirectory(), true);
                            }
                            catch (IOException ex)
                            {
                                throw new ApplicationException("Could not create an index searcher with the supplied lucene directory", ex);
                            }
                        }
                    }
                }
                else
                {
                    if (_searcher.GetReaderStatus() != ReaderStatus.Current)
                    {
                        lock (Locker)
                        {
                            //double check, now, we need to find out if it's closed or just not current
                            switch (_searcher.GetReaderStatus())
                            {
                                case ReaderStatus.Current:
                                    break;
                                case ReaderStatus.Closed:
                                    _searcher = new IndexSearcher(GetLuceneDirectory(), true);
                                    break;
                                case ReaderStatus.NotCurrent:

                                    //yes, this is actually the way the Lucene wants you to work...
                                    //normally, i would have thought just calling Reopen() on the underlying reader would suffice... but it doesn't.
                                    //here's references:
                                    // http://stackoverflow.com/questions/1323779/lucene-indexreader-reopen-doesnt-seem-to-work-correctly
                                    // http://gist.github.com/173978

                                    var oldReader = _searcher.GetIndexReader();
                                    var newReader = oldReader.Reopen(true);
                                    if (newReader != oldReader)
                                    {
                                        _searcher.Close();
                                        oldReader.Close();
                                        _searcher = new IndexSearcher(newReader);
                                    }

                                    break;
                            }
                        }
                    }
                }
            }
            else
            {
                //need to close the searcher and force a re-open

                if (_searcher != null)
                {
                    lock (Locker)
                    {
                        //double check
                        if (_searcher != null)
                        {
                            try
                            {
                                _searcher.Close();
                            }
                            catch (IOException)
                            {
                                //this will happen if it's already closed ( i think )
                            }
                            finally
                            {
                                //set to null in case another call to this method has passed the first lock and is checking for null
                                _searcher = null;
                            }

                            try
                            {
                                _searcher = new IndexSearcher(GetLuceneDirectory(), true);
                            }
                            catch (IOException ex)
                            {
                                throw new ApplicationException("Could not create an index searcher with the supplied lucene directory", ex);
                            }

                        }
                    }
                }
            }
//.........这里部分代码省略.........
开发者ID:rhayesbite,项目名称:Examine,代码行数:101,代码来源:LuceneSearcher.cs

示例9: SearchV2

        //http://www.d80.co.uk/post/2011/03/29/LuceneNet-Tutorial.aspx  Lucene.Net Tutorial with Lucene 2.9.2
        public void SearchV2(string indexDir, string q, int pageSize, int pageIndex)
        {
            indexDir = HttpContext.Current.Server.MapPath("~/Search/");
            string keywords = q;
            var search = new IndexSearcher(indexDir);

            q = GetKeyWordsSplitBySpace(q, new PanGuTokenizer());

            // 需要查询的域名称
            string[] fields = { "title", "Category", "Desc" };

            //将每个域Field所查询的结果设为“或”的关系,也就是取并集
            BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };

            //构造一个多Field查询
            Query query = MultiFieldQueryParser.Parse(Lucene.Net.Util.Version.LUCENE_29, q, fields, clauses, new PanGuAnalyzer(true));

            // 新的查询
            TopDocs newHits = search.Search(query, 100);
            ScoreDoc[] scoreDocs = newHits.ScoreDocs;

            Console.WriteLine("符合条件记录:{0}; 索引库记录总数:{1}", scoreDocs.Length, search.GetIndexReader().NumDocs());

            foreach (var hit in newHits.ScoreDocs)
            {
                var documentFromSearcher = search.Doc(hit.doc);
                Console.WriteLine(documentFromSearcher.Get("Make") + " " + documentFromSearcher.Get("Model"));
            }

            search.Close();
        }
开发者ID:jiangguang5201314,项目名称:DotNetFramework,代码行数:32,代码来源:SearchEngine.cs

示例10: WrapUnderlyingReader

		/// <summary> Given an IndexSearcher, returns a new IndexSearcher whose IndexReader 
		/// is a MultiReader containing the Reader of the original IndexSearcher, 
		/// as well as several "empty" IndexReaders -- some of which will have 
		/// deleted documents in them.  This new IndexSearcher should 
		/// behave exactly the same as the original IndexSearcher.
		/// </summary>
		/// <param name="s">the searcher to wrap
		/// </param>
		/// <param name="edge">if negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub
		/// </param>
		public static IndexSearcher WrapUnderlyingReader(IndexSearcher s, int edge)
		{
			
			IndexReader r = s.GetIndexReader();
			
			// we can't put deleted docs before the nested reader, because
			// it will throw off the docIds
            IndexReader[] readers = new IndexReader[] {
                edge < 0 ? r : IndexReader.Open(MakeEmptyIndex(0), true),
                IndexReader.Open(MakeEmptyIndex(0), true),
                new MultiReader(new IndexReader[] {
                    IndexReader.Open(MakeEmptyIndex(edge < 0 ? 4 : 0), true),
                    IndexReader.Open(MakeEmptyIndex(0), true),
                    0 == edge ? r : IndexReader.Open(MakeEmptyIndex(0), true)
                }),
                IndexReader.Open(MakeEmptyIndex(0 < edge ? 0 : 7), true),
                IndexReader.Open(MakeEmptyIndex(0), true),
                new MultiReader(new IndexReader[] {
                    IndexReader.Open(MakeEmptyIndex(0 < edge ? 0 : 5), true),
                    IndexReader.Open(MakeEmptyIndex(0), true),
                    0 < edge ? r : IndexReader.Open(MakeEmptyIndex(0), true)
                })
            };

			IndexSearcher out_Renamed = new IndexSearcher(new MultiReader(readers));
			out_Renamed.SetSimilarity(s.GetSimilarity());
			return out_Renamed;
		}
开发者ID:kstenson,项目名称:NHibernate.Search,代码行数:38,代码来源:QueryUtils.cs

示例11: TestPayloadsPos0

		public virtual void  TestPayloadsPos0()
		{
			for (int x = 0; x < 2; x++)
			{
				Directory dir = new MockRAMDirectory();
				IndexWriter writer = new IndexWriter(dir, new TestPayloadAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
				if (x == 1)
				{
					writer.SetAllowMinus1Position();
				}
				Document doc = new Document();
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
                sw.Write("a a b c d e a f g h i j a b k k");
                // flush to stream & reset it's position so it can be read
                sw.Flush();
                ms.Position = 0;
                doc.Add(new Field("content", new System.IO.StreamReader(ms)));
				writer.AddDocument(doc);
				
				IndexReader r = writer.GetReader();
				
				TermPositions tp = r.TermPositions(new Term("content", "a"));
				int count = 0;
				Assert.IsTrue(tp.Next());
				// "a" occurs 4 times
				Assert.AreEqual(4, tp.Freq());
				int expected;
				if (x == 1)
				{
					expected = System.Int32.MaxValue;
				}
				else
				{
					expected = 0;
				}
				Assert.AreEqual(expected, tp.NextPosition());
				if (x == 1)
				{
					continue;
				}
				Assert.AreEqual(1, tp.NextPosition());
				Assert.AreEqual(3, tp.NextPosition());
				Assert.AreEqual(6, tp.NextPosition());
				
				// only one doc has "a"
				Assert.IsFalse(tp.Next());
				
				IndexSearcher is_Renamed = new IndexSearcher(r);
				
				SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a"));
				SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k"));
				SpanQuery[] sqs = new SpanQuery[]{stq1, stq2};
				SpanNearQuery snq = new SpanNearQuery(sqs, 30, false);
				
				count = 0;
				bool sawZero = false;
				//System.out.println("\ngetPayloadSpans test");
				Lucene.Net.Search.Spans.Spans pspans = snq.GetSpans(is_Renamed.GetIndexReader());
				while (pspans.Next())
				{
					//System.out.println(pspans.doc() + " - " + pspans.start() + " - "+ pspans.end());
					System.Collections.Generic.ICollection<byte[]> payloads = pspans.GetPayload();
					sawZero |= pspans.Start() == 0;
					for (System.Collections.IEnumerator it = payloads.GetEnumerator(); it.MoveNext(); )
					{
						count++;
						System.Object generatedAux2 = it.Current;
						//System.out.println(new String((byte[]) it.next()));
					}
				}
				Assert.AreEqual(5, count);
				Assert.IsTrue(sawZero);
				
				//System.out.println("\ngetSpans test");
				Lucene.Net.Search.Spans.Spans spans = snq.GetSpans(is_Renamed.GetIndexReader());
				count = 0;
				sawZero = false;
				while (spans.Next())
				{
					count++;
					sawZero |= spans.Start() == 0;
					//System.out.println(spans.doc() + " - " + spans.start() + " - " + spans.end());
				}
				Assert.AreEqual(4, count);
				Assert.IsTrue(sawZero);
				
				//System.out.println("\nPayloadSpanUtil test");
				
				sawZero = false;
				PayloadSpanUtil psu = new PayloadSpanUtil(is_Renamed.GetIndexReader());
				System.Collections.Generic.ICollection<byte[]> pls = psu.GetPayloadsForQuery(snq);
				count = pls.Count;
				for (System.Collections.IEnumerator it = pls.GetEnumerator(); it.MoveNext(); )
				{
					System.String s = new System.String(System.Text.UTF8Encoding.UTF8.GetChars((byte[]) it.Current));
					//System.out.println(s);
					sawZero |= s.Equals("pos: 0");
				}
				Assert.AreEqual(5, count);
//.........这里部分代码省略.........
开发者ID:Mpdreamz,项目名称:lucene.net,代码行数:101,代码来源:TestPositionIncrement.cs

示例12: TestSetPosition

		public virtual void  TestSetPosition()
		{
			Analyzer analyzer = new AnonymousClassAnalyzer(this);
			Directory store = new MockRAMDirectory();
			IndexWriter writer = new IndexWriter(store, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
			Document d = new Document();
			d.Add(new Field("field", "bogus", Field.Store.YES, Field.Index.ANALYZED));
			writer.AddDocument(d);
			writer.Optimize();
			writer.Close();
			
			
			IndexSearcher searcher = new IndexSearcher(store);
			
			TermPositions pos = searcher.GetIndexReader().TermPositions(new Term("field", "1"));
			pos.Next();
			// first token should be at position 0
			Assert.AreEqual(0, pos.NextPosition());
			
			pos = searcher.GetIndexReader().TermPositions(new Term("field", "2"));
			pos.Next();
			// second token should be at position 2
			Assert.AreEqual(2, pos.NextPosition());
			
			PhraseQuery q;
			ScoreDoc[] hits;
			
			q = new PhraseQuery();
			q.Add(new Term("field", "1"));
			q.Add(new Term("field", "2"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(0, hits.Length);
			
			// same as previous, just specify positions explicitely.
			q = new PhraseQuery();
			q.Add(new Term("field", "1"), 0);
			q.Add(new Term("field", "2"), 1);
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(0, hits.Length);
			
			// specifying correct positions should find the phrase.
			q = new PhraseQuery();
			q.Add(new Term("field", "1"), 0);
			q.Add(new Term("field", "2"), 2);
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
			q.Add(new Term("field", "2"));
			q.Add(new Term("field", "3"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
			q.Add(new Term("field", "3"));
			q.Add(new Term("field", "4"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(0, hits.Length);
			
			// phrase query would find it when correct positions are specified. 
			q = new PhraseQuery();
			q.Add(new Term("field", "3"), 0);
			q.Add(new Term("field", "4"), 0);
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			// phrase query should fail for non existing searched term 
			// even if there exist another searched terms in the same searched position. 
			q = new PhraseQuery();
			q.Add(new Term("field", "3"), 0);
			q.Add(new Term("field", "9"), 0);
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(0, hits.Length);
			
			// multi-phrase query should succed for non existing searched term
			// because there exist another searched terms in the same searched position. 
			MultiPhraseQuery mq = new MultiPhraseQuery();
			mq.Add(new Term[]{new Term("field", "3"), new Term("field", "9")}, 0);
			hits = searcher.Search(mq, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
			q.Add(new Term("field", "2"));
			q.Add(new Term("field", "4"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
			q.Add(new Term("field", "3"));
			q.Add(new Term("field", "5"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
			q.Add(new Term("field", "4"));
			q.Add(new Term("field", "5"));
			hits = searcher.Search(q, null, 1000).ScoreDocs;
			Assert.AreEqual(1, hits.Length);
			
			q = new PhraseQuery();
//.........这里部分代码省略.........
开发者ID:Mpdreamz,项目名称:lucene.net,代码行数:101,代码来源:TestPositionIncrement.cs

示例13: DoTestSearchHitsDeleteEvery

		private void  DoTestSearchHitsDeleteEvery(int k, bool deleteInFront)
		{
			bool intermittent = k < 0;
			Log("Test search hits with " + (intermittent?"intermittent deletions.":"deletions of every " + k + " hit."));
			IndexSearcher searcher = new IndexSearcher(directory);
			IndexReader reader = searcher.GetIndexReader();
			Query q = new TermQuery(new Term(TEXT_FIELD, "text")); // matching all docs
			Hits hits = searcher.Search(q);
			Log("Got " + hits.Length() + " results");
			Assert.AreEqual(N, hits.Length(), "must match all " + N + " docs, not only " + hits.Length() + " docs!");
			if (deleteInFront)
			{
				Log("deleting hits that was not yet retrieved!");
				reader.DeleteDocument(reader.MaxDoc() - 1);
				reader.DeleteDocument(reader.MaxDoc() - 2);
				reader.DeleteDocument(reader.MaxDoc() - 3);
			}
			try
			{
				for (int i = 0; i < hits.Length(); i++)
				{
					int id = hits.Id(i);
					Assert.AreEqual(i, hits.Id(i), "Hit " + i + " has doc id " + hits.Id(i) + " instead of " + i);
					if ((intermittent && (i == 50 || i == 250 || i == 950)) || (!intermittent && (k < 2 || (i > 0 && i % k == 0))))
					{
						Document doc = hits.Doc(id);
						Log("Deleting hit " + i + " - doc " + doc + " with id " + id);
						reader.DeleteDocument(id);
					}
					if (intermittent)
					{
						// check internal behavior of Hits (go 50 ahead of getMoreDocs points because the deletions cause to use more of the available hits)
						if (i == 150 || i == 450 || i == 1650)
						{
							Assert.IsTrue(hits.debugCheckedForDeletions, "Hit " + i + ": hits should have checked for deletions in last call to getMoreDocs()");
						}
						else if (i == 50 || i == 250 || i == 850)
						{
							Assert.IsFalse(hits.debugCheckedForDeletions, "Hit " + i + ": hits should have NOT checked for deletions in last call to getMoreDocs()");
						}
					}
				}
			}
			catch (System.Exception e)
			{
				// this is the only valid exception, and only when deletng in front.
				Assert.IsTrue(deleteInFront, e.Message + " not expected unless deleting hits that were not yet seen!");
			}
			searcher.Close();
		}
开发者ID:kstenson,项目名称:NHibernate.Search,代码行数:50,代码来源:TestSearchHitsWithDeletions.cs

示例14: GetValues

        /// <summary>
        /// Gets all distinct values (values are the vertex IDs).
        /// </summary>
        /// 
        /// <param name="select">A predicate which takes a LuceneEntry and returns whether a LuceneEntry should be taken into account when looking for vertex ids.
        ///						 If this parameter is NULL, no Lucene entry is ignored.</param>
        /// 
        /// <returns>
        /// A collection containing a single set of Int64 values, representing the distinct vertex ids within the Lucene index;
        /// or a collection containing an empty set, if no entries are within the index.
        /// </returns>
        public LuceneValueList GetValues(Predicate<LuceneEntry> select = null)
        {
            var searcher = new IndexSearcher(_IndexDirectory, true);
            var reader = searcher.GetIndexReader();

            if (select == null)
            {
                var ret = new LuceneValueList(reader);
                return ret;
            }
            else
            {
                var ret = new LuceneValueList(reader, select);
                return ret;
            }
        }
开发者ID:anukat2015,项目名称:sones,代码行数:27,代码来源:LuceneIndex.cs

示例15: GetBits

        public ISearchBits GetBits()
        {
            var query = CreateQuery();
            IndexSearcher searcher;

            try {
                searcher = new IndexSearcher(_directory, true);
            }
            catch {
                // index might not exist if it has been rebuilt
                Logger.Information("Attempt to read a none existing index");
                return null;
            }

            try {
                var filter = new QueryWrapperFilter(query);
                var bits = filter.GetDocIdSet(searcher.GetIndexReader());
                var disi = new OpenBitSetDISI(bits.Iterator(), searcher.MaxDoc());
                return new SearchBits(disi);
            }
            finally {
                searcher.Close();
            }
        }
开发者ID:Timbioz,项目名称:SciGitAzure,代码行数:24,代码来源:LuceneSearchBuilder.cs


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