[Lucene]挖掘相关搜索词

2014-11-24 09:17:14 · 作者: · 浏览: 0
搜索引擎中往往有一个可选的搜索词的列表,当搜索结果太少时,可以帮助用户扩展搜索内容,或者搜索结果太多的时候可以帮助用户深入定向搜索。一种方法是从搜索日志中挖掘字面相似的词作为相关搜索词列表。另一种方法是把用户共同查询的词作为相关搜索词,需要有搜索日志才能实现。【摘自《Lucene In Action》】
下面使用的是第一种方法:
[java]
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 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;
}
}
测试代码:
[java]
@Test
public void test() throws IOException, ParseException {
// fail("Not yet implemented");
HashSet words = new HashSet();
// 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]);
}
}
测试结果:
[java]
搜索内容:Spring 料
相 搜索匹配 果:
java 料下
Lucene入 料
Spring原理解析