import java.io.File; import java.io.IOException; publicclassIndex{ publicstaticvoidmain(String[] args)throws IOException { //Codec codec = new SimpleTextCodec(); Codec codec = new HexinCodec(); //Codec codec = new Lucene46Codec(); String INDEX_DIR = "e:\\index"; Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_48); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_48, analyzer); iwc.setCodec(codec); IndexWriter writer = null; iwc.setOpenMode(OpenMode.CREATE); iwc.setUseCompoundFile(false); try { writer = new IndexWriter(FSDirectory.open(new File(INDEX_DIR)), iwc); Document doc = new Document(); doc.add(new TextField("title", "who are you, you are a man", Field.Store.YES)); doc.add(new TextField("content", "A long way to go there. Please drive a car", Field.Store.NO)); writer.addDocument(doc); doc = new Document(); doc.add(new TextField("title", "are you sure", Field.Store.YES)); doc.add(new TextField("content", "He is a good man. He is a driver", Field.Store.NO)); writer.addDocument(doc); writer.commit(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
String index = "e:\\index"; IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index))); IndexSearcher searcher = new IndexSearcher(reader); String queryString = "driver"; Query query = new TermQuery(new Term("content", queryString)); System.out.println("Searching for: " + query.toString()); Date start = new Date(); TopDocs results = searcher.search(query, null, 100); Date end = new Date(); System.out.println("Time: "+(end.getTime()-start.getTime())+"ms"); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < hits.length; i++) { String output = ""; Document doc = searcher.doc(hits[i].doc); output += "doc="+hits[i].doc+" score="+hits[i].score; String title = doc.get("title"); if (title != null) { output += " " + title; } System.out.println(output); } reader.close(); } }
在Eclipse中运行Index.java,此时会报错 A SPI class of type org.apache.lucene.codecs.Codec with name ‘Lucene46’ does not exist. You need to add the corresponding JAR file supporting this SPI to your classpath.The current classpath supports the following names:[]