- public static void main(String[] args) throws CorruptIndexException, LockObtainFailedException, IOException, ParseException {
- Analyzer analyzer = new SimpleAnalyzer();
- // Store the index in memory:
- Directory directory = new RAMDirectory();
- // To store an index on disk, use this instead:
- //Directory directory = FSDirectory.open("/tmp/testindex");
- IndexWriter iwriter = new IndexWriter(directory, analyzer, true, new IndexWriter.MaxFieldLength(25000));
- Document doc = new Document();
- String text = "This is the text to is be indexed.";
- doc.add(new Field("fieldname", text, Field.Store.YES, Field.Index.ANALYZED));
- iwriter.addDocument(doc);
- iwriter.close();
- // Now search the index:
- IndexSearcher isearcher = new IndexSearcher(directory, true); // read-only=true
- // Parse a simple query that searches for "text":
- QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
- Query query = parser.parse("is");
- ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
- System.out.println(hits.length);
- // Iterate through the results:
- for (int i = 0; i < hits.length; i++) {
- Document hitDoc = isearcher.doc(hits[i].doc);
- System.out.println(hitDoc.get("fieldname"));
- }
- isearcher.close();
- directory.close();
- }
- //该片段来自于http://www.codesnippet.cn/detail/160120131688.html
来源: http://www.codesnippet.cn/detail/160120131688.html