The Lucene command-line demo
First, you should download the latest Lucene distribution and then extract it to a working directory.
1.open a gnome-terminater
2.Setting your CLASSPATH,you need 4 jars like this ,
export LUENCE_HOME=/opt/lucene-6.0.1
export CLASSPATH= LUENCEDEMO/lib/lucene−analyzers−common−6.0.1.jar: LUENCEDEMO/lib/lucene-demo-6.0.1.jar: LUENCEDEMO/lib/lucene−queryparser−6.0.1.jar: LUENCEDEMO/lib/lucene-core-6.0.1.jar
make index,indexing files
java org.apache.lucene.demo.IndexFiles -docs $LUENCE_HOMETo search the index type:
java org.apache.lucene.demo.SearchFilestype keywords what you will search after it
note:
IndexFiles.java: code to create a Lucene index.
SearchFiles.java: code to search a Lucene index.
java code test:
public static void main(String[] args) throws IOException, ParseException {
Analyzer analyzer = new StandardAnalyzer();
//create index writer configuration
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
//store method 1:store in memory
// RAMDirectory dir = new RAMDirectory();
//store method 2:store in fs
//specified store index directory
Directory dir = NIOFSDirectory.open(Paths.get("/home/cypress/Test/LunceTest"));
IndexWriter writer = new IndexWriter(dir, iwc);
// make index
ArrayList<Document> arrayList = new ArrayList<>();
indexing(arrayList, "title", 1L, " I love you forever");
indexing(arrayList, "title", 2L, " will you love me ?");
// writer.addDocument(document);
writer.addDocuments(arrayList);
writer.close();
//for search
// open the indexed directory just we have created
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
// parse keyword
Query parse = new QueryParser("title", analyzer).parse("me");
TopDocs res = searcher.search(parse, 5);
System.out.println("Hits:" + res.totalHits);
ScoreDoc[] hits = res.scoreDocs;
for (ScoreDoc scoreDoc : hits) {
Document doc = searcher.doc(scoreDoc.doc);
System.out.println(doc.get("title") + "id:" + doc.get("id"));
}
}
/**
* <p>add document to collection ,for batching writer indexes and return it</p>
* @param arrayList :add document to this collection
* @param field: store field
* @param id :data base record id
* @param context :detail of the record
* @return
*/
private static ArrayList<Document> indexing(ArrayList<Document> arrayList, String field, Long id, String context) {
Document document = new Document();
document.add(new TextField(field, context, Store.YES));
document.add(new StoredField("id", id));
arrayList.add(document);
return arrayList;
}
link: https://lucene.apache.org/core/6_0_1/demo/overview-summary.html#Setting_your_CLASSPATH