import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Sort;
public class TestSearch
{
public static final String indexpath = "/root/index";
public static void main(String args[]) throws Exception
{
IndexWriter writer = new IndexWriter(indexpath, new StandardAnalyzer(), true);
Document doc1 = new Document();
Field field1 = new Field("booknum", "00001", Field.Store.YES, Field.Index.UN_TOKENIZED);
Field field2 = new Field("content", "fan fei", Field.Store.YES, Field.Index.TOKENIZED);
doc1.add(field1);
doc1.add(field2);
Document doc2 = new Document();
Field field3 = new Field("booknum", "00002", Field.Store.YES, Field.Index.UN_TOKENIZED);
Field field4 = new Field("content", "fan song", Field.Store.YES, Field.Index.TOKENIZED);
doc2.add(field3);
doc2.add(field4);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.close();
IndexSearcher searcher = new IndexSearcher(indexpath);
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse("fan");
Sort sort = new Sort();
sort.setSort("booknum", true); // reverse sort
Hits hits = searcher.search(query, sort);
for (int i = 0; i < hits.length(); i++)
System.out.println(hits.doc(i));
}
}
|