您的位置:首页 > 产品设计 > UI/UE

Luence command-line demo

2016-06-02 21:57 323 查看
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_HOME

To search the index type:

java org.apache.lucene.demo.SearchFiles

type 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: