- Lucene 4 Cookbook
- Edwood Ng Vineeth Mohan
- 258字
- 2021-07-16 14:07:48
Creating and writing documents to an index
This recipe shows you how to index a document. In fact, here we are putting together all that we learned so far from the previous recipes. Let's see how it is done.
How to do it...
The following code sample shows you an example of adding a simple document to an index:
public class LuceneTest { public static void main(String[] args) throws IOException { Analyzer analyzer = new WhitespaceAnalyzer(); Directory directory = new RAMDirectory(); IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer); IndexWriter indexWriter = new IndexWriter(directory, config); Document doc = new Document(); String text = "Lucene is an Information Retrieval library written in Java"; doc.add(new TextField("fieldname", text, Field.Store.YES)); indexWriter.addDocument(doc); indexWriter.close(); } }
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
How it works…
Note that the preceding code snippet combined all the sample codes we learned so far. It first initializes an analyzer, directory, IndexWriterConfig
, and IndexWriter
. Once the IndexWriter is obtained, a new Document is created with a custom TextField
. The Document is then added to IndexWriter. Also, note that we call indexWriter.close()
at the end. calling this method, will commit all changes and close the index.
The IndexWriter
class exposes an addDocument(doc)
method that allows you to add documents to an index. IndexWriter
will write to an index specified by directory.
- TypeScript入門與實(shí)戰(zhàn)
- Java范例大全
- Developing Mobile Web ArcGIS Applications
- 三維圖形化C++趣味編程
- 跟老齊學(xué)Python:輕松入門
- R語(yǔ)言數(shù)據(jù)可視化實(shí)戰(zhàn)
- SQL語(yǔ)言從入門到精通
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- Python程序設(shè)計(jì)
- Flutter跨平臺(tái)開發(fā)入門與實(shí)戰(zhàn)
- 持續(xù)集成與持續(xù)交付實(shí)戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- Learning VMware vSphere
- Go Systems Programming
- 信息學(xué)奧林匹克競(jìng)賽初賽精講精練
- Distributed Computing with Python