package com.robert.lucene; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.SearcherFactory; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import java.util.concurrent.Callable; /** * Created on 15/8/21. */ public class SearchArray { public static void main(String[] args) { try { Directory directory = new RAMDirectory(); Analyzer analyzer = new SimpleAnalyzer(); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); IndexWriter writer = new IndexWriter(directory, iwc); String[] docs = { "a b c d e", "a b c d e f g h", "a b c d e f g h i j", "a c e", "e c a", "a c e a c e", "a c e a b c", }; for (int j = 0; j < docs.length; ++j) { Document d = new Document(); d.add(new TextField("contents", docs[j], Field.Store.YES)); writer.addDocument(d); } writer.close(); IndexReader reader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(reader); //搜索contents字段 QueryParser parser = new QueryParser("contents", analyzer); TopDocs topDocs = null; String[] queries = { "a c e", "h i" }; for( int j = 0; j < queries.length; ++j) { Query query = parser.parse(queries[j]); System.out.println(" query:" + query.toString("contents")); topDocs = indexSearcher.search(query,100); System.out.println("总共匹配多少个:" + topDocs.totalHits); for(int i = 0; i < topDocs.totalHits; ++i) { Document d = indexSearcher.doc(topDocs.scoreDocs[i].doc); System.out.println(i + " " + topDocs.scoreDocs[i].score + d.get("contents")); } System.out.println("-------------"); } } catch (Exception e) { } } }
luncene RAMDirectory
最新推荐文章于 2021-02-23 13:19:09 发布