Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.PrintStream;
- import org.apache.lucene.analysis.standard.StandardAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.StringField;
- import org.apache.lucene.document.Field.Store;
- import org.apache.lucene.index.DirectoryReader;
- import org.apache.lucene.index.IndexWriter;
- import org.apache.lucene.index.IndexWriterConfig;
- import org.apache.lucene.index.IndexableField;
- import org.apache.lucene.index.Term;
- import org.apache.lucene.search.IndexSearcher;
- import org.apache.lucene.search.MatchAllDocsQuery;
- import org.apache.lucene.search.Query;
- import org.apache.lucene.search.ScoreDoc;
- import org.apache.lucene.search.TermQuery;
- import org.apache.lucene.store.RAMDirectory;
- import org.apache.lucene.util.Version;
- public class ReindexTest {
- static RAMDirectory dir = new RAMDirectory();
- static Version version = Version.LUCENE_4_10_0;
- static IndexWriterConfig config = new IndexWriterConfig(version, new StandardAnalyzer());
- static IndexWriter iw;
- static String teststring = "abc def";
- public static void main(String[] args) throws Exception {
- iw = new IndexWriter(dir, config);
- Document doc = new Document();
- doc.add(new StringField("a", teststring, Store.YES));
- doc.add(new StringField("b", "a", Store.YES));
- iw.addDocument(doc);
- Term term = new Term("a", teststring);
- System.out.println("Term query");
- for (Document docs : search(term))
- printDocument(docs, System.out);
- doc = search(term)[0];
- doc.removeField("b");
- doc.add(new StringField("b", "b", Store.YES));
- iw.updateDocument(term, doc);
- iw.commit();
- iw.waitForMerges();
- iw.close();
- iw = new IndexWriter(dir, new IndexWriterConfig(version, new StandardAnalyzer()));
- System.out.println("All docs");
- for (Document docs : search(new MatchAllDocsQuery()))
- printDocument(docs, System.out);
- System.out.println("Term query");
- for (Document docs : search(term))
- printDocument(docs, System.out);
- }
- public static Document[] search(Term t) throws IOException {
- TermQuery q = new TermQuery(t);
- return search(q);
- }
- public static Document[] search(Query q) throws IOException {
- DirectoryReader reader = DirectoryReader.open(iw, true);
- IndexSearcher search = new IndexSearcher(reader);
- ScoreDoc[] results = search.search(q, 100).scoreDocs;
- Document[] docs = new Document[results.length];
- for (int i = 0; i < docs.length; i++)
- docs[i] = search.doc(results[i].doc);
- return docs;
- }
- public static void printDocument(Document doc, PrintStream output) {
- for (IndexableField field : doc.getFields()) {
- output.println(field.toString());
- }
- output.println("------------------------------------");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment