{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Java Lucene Version 3.0.0 In-Memory Or Memory Text Search Example

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.util.Version;


public void simpleLucene() throws CorruptIndexException, LockObtainFailedException, IOException, ParseException {
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

        // Store the index in memory:
        Directory directory = new RAMDirectory();

        // To store an index on disk, use this instead (note that the
        // parameter true will overwrite the index in that directory
        // if one exists):
        // Directory directory = FSDirectory.open(new File("/tmp/testindex"));

        IndexWriter iwriter = new IndexWriter(directory, analyzer, true, new IndexWriter.MaxFieldLength(25000));

        Document doc = new Document();
        String text = "This is the st. text to be indexed1.";
        doc.add(new Field("fieldname", text, Field.Store.YES, Field.Index.ANALYZED));
        doc = new Document();
        text = "This is the st text to be indexed2.";
        doc.add(new Field("fieldname", text, Field.Store.YES, Field.Index.ANALYZED));

        // Now search the index:
        IndexSearcher isearcher = new IndexSearcher(directory);

        // Parse a simple query that searches for "text":
        QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
        Query query = parser.parse("st.");

        TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
        isearcher.search(query, collector);

        System.out.println("collector.getTotalHits()=" + collector.getTotalHits());
//        assertEquals(2, collector.getTotalHits());

        // Iterate through the results:
        ScoreDoc[] hits = collector.topDocs().scoreDocs;
        for (int i = 0; i < hits.length; i++) {
            Document hitDoc = isearcher.doc(hits[i].doc);
            System.out.println("hitDoc.get(\"fieldname\")=" + hitDoc.get("fieldname"));

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks