⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 phrasequerytest.cs

📁 DotLucentet,用来做撬
💻 CS
字号:
using System;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using NUnit.Framework;
namespace dotLucene.inAction.BasicSearch
{
	[TestFixture]
	public class PhraseQueryTest
	{
		private IndexSearcher searcher;

		private RAMDirectory directory;


		[SetUp]
		protected void Init()
		{
			directory = new RAMDirectory();

			// set up sample document
			IndexWriter writer = new IndexWriter(directory,
				new WhitespaceAnalyzer(), true);
			Document doc = new Document();
			doc.Add(Field.Text("field",
				"the quick brown fox jumped over the lazy dog"));
			writer.AddDocument(doc);
			writer.Close();

			searcher = new IndexSearcher(directory);
		}

		private bool matched(String[] phrase, int slop)
		{
			PhraseQuery query = new PhraseQuery();
			query.SetSlop(slop);

			for (int i = 0; i < phrase.Length; i++)
			{
				query.Add(new Term("field", phrase[i]));
			}

			Hits hits = searcher.Search(query);
			return hits.Length() > 0;
		}

		[Test]
		public void SlopComparison()
		{
			String[] phrase = new String[] {"quick", "fox"};

			Assert.IsFalse(matched(phrase, 0), "exact phrase not found");

			Assert.IsTrue(matched(phrase, 1), "close enough");
		}


		[Test]
		public void Reverse()

		{
			String[] phrase = new String[] {"fox", "quick"};

			Assert.IsFalse(matched(phrase, 2), "exact phrase not found");

			Assert.IsTrue(matched(phrase, 3), "close enough");
		}

		[Test]
		public void Multiple()

		{
			Assert.IsFalse(matched(new String[] {"quick", "jumped", "lazy"}, 3), "not close enough");

			Assert.IsTrue(matched(new String[] {"quick", "jumped", "lazy"}, 4), "just enough");

			Assert.IsFalse(matched(new String[] {"lazy", "jumped", "quick"}, 7), "almost but not quite");

			Assert.IsTrue(matched(new String[] {"lazy", "jumped", "quick"}, 8), "bingo");

		}

		[Test]
		public void TestQueryParser()
		{
			Query q1 = QueryParser.Parse("\"quick fox\"",
				"field", new SimpleAnalyzer());
			Hits hits1 = searcher.Search(q1);
			Assert.AreEqual(hits1.Length(), 0);

			Query q2 = QueryParser.Parse("\"quick fox\"~1",
				"field", new SimpleAnalyzer());
			Hits hits2 = searcher.Search(q2);
			Assert.AreEqual(hits2.Length(), 1);

			QueryParser qp = new QueryParser("field", new SimpleAnalyzer());
			qp.SetPhraseSlop(1);
			Query q3=qp.Parse("\"quick fox\"");
			Assert.AreEqual("\"quick fox\"~1", q3.ToString("field"),"sloppy, implicitly");
			Hits hits3 = searcher.Search(q2);
			Assert.AreEqual(hits3.Length(), 1);
	
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -