Lucene Version: 7.1
Key points for using Lucene
- Create a document, add a file (Field);
- Add documents to IndexWriter;
- Use Queryparser.parse () to build the query content;
- Use the search () method of indexsearcher to make inquiries;
First, the basic process of creating an index
Open a Directory, storing index files
Fsdirectory refers to a folder that can be stored in a cache ramdirectory
Indexpath: File path
Directory dir = Fsdirectory.open (Paths.get (Indexpath));
Instantiate Analyzer, working with text files
StandardAnalyzer uses the Unicode text segmentation algorithm to convert the symbols to lowercase, filtering out the usual terms
Different types of analyzer are required for different languages, see: https://lucene.apache.org/core/7_1_0/analyzers-common/overview-summary.html
Analyzer Analyzer = new StandardAnalyzer ();
Index configuration Content
Indexwriterconfig IWC = new Indexwriterconfig (analyzer);
Create,append,create_or_append
Iwc.setopenmode (openmode.create);
Instantiate IndexWriter
IndexWriter writer = new IndexWriter (dir, IWC);
Instantiate document, which indicates the text content of the file and the creation time and location information, etc.
Document doc = new document ();
"Path": Index field
Doc.add (New Stringfield ("Path", file.tostring (), Field.Store.YES));
Doc.add (New Longpoint ("Modified", lastmodified));
Doc.add (New TextField ("Contents", New BufferedReader (new InputStreamReader (Stream, standardcharsets.utf_8)));
Add to IndexWriter
Writer.adddocument (DOC);
Shut down
Writer.close ();
Second, the search basic process
Indexreader reader = Directoryreader.open (Fsdirectory.open (Paths.get (index)));
Indexsearcher searcher = new Indexsearcher (reader);
Analyzer Analyzer = new StandardAnalyzer ();
Indexed fields
Queryparser parser = new Queryparser ("contents", analyzer);
Query results
Query query = parser.parse ("123456");
Topdocs results = searcher.search (query, 5 * hitsperpage);
Scoredoc[] hits = Results.scoredocs;
Getting started with Lucene-how to write a Lucene program