【Lucene】挖掘相关搜索词

搜索引擎中往往有一个可选的搜索词的列表,当搜索结果太少时,可以帮助用户扩展搜索内容,或者搜索结果太多的时候可以帮助用户深入定向搜索。一种方法是从搜索日志中挖掘字面相似的词作为相关搜索词列表。另一种方法是把用户共同查询的词作为相关搜索词,需要有搜索日志才能实现。【摘自《Lucene In Action》】

下面使用的是第一种方法:

 

package com.tan.code;



//省略引入



public class RelateWords {

	private static final String TEXT_FIELD = "text";



	/**

	 * 

	 * @param words 候選相関詞列表

	 * @param word 相關搜索詞的種子詞

	 * @return 

	 * @throws IOException

	 * @throws ParseException

	 */

	static public String[] filterRelated(HashSet<String> words, String word)

			throws IOException, ParseException {



		//RAMDirectory ramDirectory = new RAMDirectory();

		Directory directory=new SimpleFSDirectory(new File("E://related"));

		IndexWriter indexWriter = new IndexWriter(directory,

				new IndexWriterConfig(Version.LUCENE_43, new IKAnalyzer(true)));

		for (String text : words) {

			Document document = new Document();

			document.add(new TextField(TEXT_FIELD, text, Store.YES));

			indexWriter.addDocument(document);

		}

		indexWriter.close();

		IndexReader indexReader = DirectoryReader.open(directory);

		IndexSearcher indexSearcher = new IndexSearcher(indexReader);

		QueryParser queryParser = new QueryParser(Version.LUCENE_43,

				TEXT_FIELD, new IKAnalyzer(true));

		Query query = queryParser.parse(word);

		TopDocs td = indexSearcher.search(query, 10);

		ScoreDoc[] sd = td.scoreDocs;

		String relateWords[] = new String[sd.length];

		for (int i = 0; i < sd.length; i++) {

			int z = sd[i].doc;

			Document doc = indexSearcher.doc(z);

			relateWords[i] = doc.get(TEXT_FIELD);

		}

		indexReader.close();

		//ramDirectory.close();

		directory.close();

		return relateWords;



	}



}


测试代码:

 

 

	@Test

	public void test() throws IOException, ParseException {

		// fail("Not yet implemented");

		HashSet<String> words = new HashSet<String>();



		// words.add("Lucene");

		// words.add("Lucene入門資料");

		// words.add("java資料下載");

		// words.add("SQL詳解");

		// words.add("揭祕Lucene原理");

		// words.add("Spring原理解析");

		// words.add("什麽是Lucene?怎麽樣才可以學好Lucene呢?");



		String word = "Spring資料";



		String rewords[] = RelateWords.filterRelated(words, word);

		System.out.println("搜索内容:" + word);

		System.out.println("相關搜索匹配結果:");

		for (int i = 0; i < rewords.length; i++) {

			System.out.println(rewords[i]);

		}

	}


测试结果:

 

 

搜索内容:Spring資料

相關搜索匹配結果:

java資料下載

Lucene入門資料

Spring原理解析


 



 

你可能感兴趣的:(Lucene)