Lucene搜索引擎的使用

@Test
public static void createDocument() throws IOException {
// 定义文档
Document document = new Document();
// 商品id做存储
// IndexableField
document.add(new LongField("id", 856645L, Store.YES));
document.add(new TextField("title", "华棋皓.你快搭两蚊纸摩托车来睇我咯涡.要死嗲哇!三星 Galaxy S4 (I9500) 16G版 星空黑 联通3G手机", Store.YES));
document.add(new TextField("sellPoint", "年货特价来袭!三星经典旗舰机!", Store.YES));
document.add(new LongField("price", 1888000L, Store.YES));
document.add(new StringField("image",
"http://image.taotao.com/jd/2cd67c806e054435bce4c931a731493a.jpg", Store.YES));
// 定义标准分词
Analyzer analyzer = new IKAnalyzer();
// 定义目录
Directory directory = FSDirectory.open(new File("index"));
// 定义lucene版本的indexWriter配置
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_2, analyzer);
// 定义indexWriter
IndexWriter indexWriter = new IndexWriter(directory, config);

// 写入数据
indexWriter.addDocument(document);
// 提交并关闭
indexWriter.commit();
indexWriter.close();

System.out.println("OK");
}
@Test
public static void testSearch() throws IOException, ParseException {
// 定义目录
Directory directory = FSDirectory.open(new File("index"));
// 定义阅读器
IndexReader indexReader = DirectoryReader.open(directory);
// 构建搜索索引对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);

// 定义标准分词器
Analyzer analyzer = new IKAnalyzer();
// 定义搜索条件
QueryParser queryParser = new QueryParser("title", analyzer);
//在搜索条件中加入分词
Query query = queryParser.parse("华棋皓");

// Query query = new TermQuery(new Term("sellPoint", "旗舰机"));
// 执行搜索:n 搜索的记录数
TopDocs topDocs = indexSearcher.search(query, 10);

System.out.println("命中的文档数:" + topDocs.totalHits);

// 取出文档集合
ScoreDoc[] scoreDocs = topDocs.scoreDocs;

for (ScoreDoc scoreDoc : scoreDocs) {
System.out.println("得分:" + scoreDoc.score);
// 通过文档id对象
Document document = indexSearcher.doc(scoreDoc.doc);
System.out.println("id=" + document.get("id"));
System.out.println("title=" + document.get("title"));
System.out.println("sellPoint=" + document.get("sellPoint"));
System.out.println("image=" + document.get("image"));
System.out.println("price=" + document.get("price"));
}

indexReader.close();
}
public static void main(String[] args) throws IOException, ParseException {
    testSearch();
}
上一篇:关于Lucene的概念


下一篇:java – SOLR – PathHierarchyTokenizerFactory Facet Query