lucene5(4)修改指定索引的搜索权重

1、介绍

lucene可以对指定索引的字段修改搜索权重,使权重大的索引优先显示

2、代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Test
public void TestBoot() throws Exception {
IndexWriter writer = getIndexWriter(indexDir);
Document document = new Document();
// 添加一个文档信息,相当于一个数据库表字段
Field nameField = new TextField("name", "hello world", Field.Store.YES);
// 权值默认1,该值越大排名越前
nameField.setBoost(1.5F);
document.add(nameField);
document.add(new TextField("describes", "测试luence", Field.Store.YES));
writer.addDocument(document);
writer.close();
}

@Test
public void TestSearch() throws Exception {
IndexReader reader = getIndexReader();
IndexSearcher searcher = new IndexSearcher(reader);
// 指定Document的某个属性
QueryParser parser = new QueryParser("name", getAnalyzer());
// 指定索引内容,对应某个分词
Query query = parser.parse("hello");
TopDocs hits = searcher.search(query, 10);
for (ScoreDoc sd : hits.scoreDocs) {
Document doc = searcher.doc(sd.doc);
//显示搜索结果的评分(评分=权重*搜索匹配评分)
System.out.println("name:" + doc.get("name") + ",评分:"+sd.score);
}
reader.close();
}
>