Skip to content

Instantly share code, notes, and snippets.

@zzzfree
Last active December 14, 2015 16:18
Show Gist options
  • Save zzzfree/5113763 to your computer and use it in GitHub Desktop.
Save zzzfree/5113763 to your computer and use it in GitHub Desktop.
Lucene Search
// http://www.cnblogs.com/lcuzhanglei/archive/2012/08/01/2618381.html
// 对于要排序的字段,在索引的时候可以Field.Index.NOT_ANALYZED
import org.apache.lucene.analysis.Analyzer
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.IndexReader
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.QueryParser
import org.apache.lucene.search.IndexSearcher
import org.apache.lucene.search.Query
import org.apache.lucene.search.Sort
import org.apache.lucene.search.SortField
import org.apache.lucene.search.TopDocs
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.search.ScoreDoc;
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File("./db")));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
// Analyzer analyzer = new IKAnalyzer();
// searcher.setSimilarity(new IKSimilarity());
// Query query = IKQueryParser.parse(name, "衣服");
def field = "contents"
QueryParser parser = new QueryParser(Version.LUCENE_41, field, analyzer);
Query query = parser.parse("门");
def pageSize = 10
Sort sort = new Sort();
SortField sortField = new SortField("path",SortField.Type.STRING,true );
sort.setSort(sortField)
TopDocs results = searcher.search(query, pageSize,sort);
def show = {
// print results
println "-------------------------------------"
ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
println(numTotalHits + " total matching documents");
hits.each{
println "path:" + searcher.doc(it.doc).get("path");
println "contents:" + searcher.doc(it.doc).get("contents");
}
}
show()
// next page
results = searcher.searchAfter(results.scoreDocs[results.scoreDocs.size()-1] , query, pageSize, sort)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment