Lucene

Java library for high-performance text search. Works by creating/searching an optimized index.

The code below has been tested with Lucene 2.3.2

Indexing

// create index
IndexWriter writer = new IndexWriter(new File("/just/a/path/testIndex"), new StandardAnalyzer(), true);			
 
// create document
Document doc = new Document();
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.add(new Field("name", "Just a name", Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("multifield", "toto\ntata", Field.Store.YES, Field.Index.TOKENIZED));
 
// you may want to delete in the index any already existing document with the same id
writer.deleteDocuments(new Term("id", "5"));
 
// add document to index
writer.addDocument(doc);
writer.flush();
 
// create/add other documents
//...
  • Field.Store.YES: if you need to get this value from the search result list. Otherwise it's just indexed and discarded.
  • Field.Index.TOKENIZED: if this value needs to be indexed (it will be used in the search query). Otherwise you'll get it only from the results.

Searching

// get index
IndexSearcher indexSearcher = new IndexSearcher("/just/a/path/testIndex");
 
// create query
BooleanQuery booleanQuery = new BooleanQuery();
 
// add clause to query
QueryParser parser = new QueryParser("name", new StandardAnalyzer());
booleanQuery.add(parser.parse("Just a name"), BooleanClause.Occur.MUST);
 
// create/add other clauses to query
//...
 
// execute query on index
Hits hits = indexSearcher.search(booleanQuery);
 
// use results
for(int i = 0; i < hits.length(); i++) {
  String id = hits.doc(i).get("id");
  //...
}

Download working example

Includes indexing, multi-criteria and multi-field search: Eclipse project with all dependencies.

Reference

Feedback

adadasd
adasd
May 14, 2010
#1
Very simple and nice web site.
Ashish kumar Srivastav
May 14, 2010
#2
The link to "Ke CAI Blog: Lucene Simplest" is dead.
Andreas Kuckartz
Sep 12, 2010
#3
studying....
QipanLee
Apr 22, 2011
#4
good
good
Oct 15, 2013
#5