示例比较简单,就是简单对索引中的一个存在的document进行内容的修改。
package com.cn;
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.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
public class TT {
public static void main(String []args) throws Exception {
String [] ids = {"1","2","3"};
String [] contents = {"shenyang is a city","dalian is a city","jinzhou is a city"};
String [] city = {"shenyang","dalian","jinzhou"};
Directory directory = new RAMDirectory();;
IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34)));
for(int i = 0;i < ids.length;i++){
Document doc = new Document();
doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
doc.add(new Field("contents",contents[i],Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("city",city[i],Field.Store.YES,Field.Index.ANALYZED));
indexWriter.addDocument(doc);
}
System.out.println("total:"+indexWriter.numDocs());
indexWriter.close();
queryMethod(directory,"city","shenyang");
queryMethod(directory,"city","yinkou");
indexWriter = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34)));
Document doc = new Document();
doc.add(new Field("id","1",Field.Store.YES,Field.Index.NOT_ANALYZED));
doc.add(new Field("contents","yinkou is a city smaller than shenyang",Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("city","yinkou",Field.Store.YES,Field.Index.ANALYZED));
indexWriter.updateDocument(new Term("id","1"), doc);
indexWriter.close();
System.out.println("\nindex is changed\n");
queryMethod(directory,"city","shenyang");
queryMethod(directory,"city","yinkou");
}
public static void queryMethod(Directory directory,String item,String txt)throws Exception {
Term term = new Term(item,txt);
Query query = new TermQuery(term);
IndexSearcher indexSearcher = new IndexSearcher(directory);
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("it has "+topDocs.totalHits+" "+txt+" in "+item);
ScoreDoc [] scoreDoc = topDocs.scoreDocs;
for(int i=0;i<scoreDoc.length;i++){
Document d = indexSearcher.doc(scoreDoc[i].doc);
System.out.println("city:"+d.get("city"));
System.out.println("contents:"+d.get("contents"));
}
}
}