我是文本搜索的新手,我正在研究一些与 lucene 相关的示例。我从这个链接中找到了一个例子。http://javatechniques.com/blog/lucene-in-memory-text-search-example/我在我的eclipse IDE中试过了。但它给出了一些错误。我也导入了所有相关的 jar 文件。
这是代码:
公共类 InMemoryExample {
public static void main(String[] args) { // Construct a RAMDirectory to hold the in-memory representation // of the index. RAMDirectory idx = new RAMDirectory(); try { // Make an writer to create the index IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(Version.LUCENE_48),
IndexWriter.MaxFieldLength.LIMITED);
// Add some Document objects containing quotes writer.addDocument(createDocument("Theodore Roosevelt", "It behooves every man to remember that the work of the " + "critic, is of altogether secondary importance, and that, " + "in the end, progress is accomplished by the man who does " + "things.")); writer.addDocument(createDocument("Friedrich Hayek", "The case for individual freedom rests largely on the " + "recognition of the inevitable and universal ignorance " + "of all of us concerning a great many of the factors on " + "which the achievements of our ends and welfare depend.")); writer.addDocument(createDocument("Ayn Rand", "There is nothing to take a man's freedom away from " + "him, save other men. To be free, a man must be free " + "of his brothers.")); writer.addDocument(createDocument("Mohandas Gandhi", "Freedom is not worth having if it does not connote " + "freedom to err.")); // Optimize and close the writer to finish building the index writer.optimize(); writer.close(); // Build an IndexSearcher using the in-memory index Searcher searcher = new IndexSearcher(idx); // Run some queries search(searcher, "freedom"); search(searcher, "free"); search(searcher, "progress or achievements"); searcher.close(); } catch (IOException ioe) { // In this example we aren't really doing an I/O, so this // exception should never actually be thrown. ioe.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } } /** * Make a Document object with an un-indexed title field and an * indexed content field. */ private static Document createDocument(String title, String content) { Document doc = new Document(); // Add the title as an unindexed field... doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO)); // ...and the content as an indexed field. Note that indexed // Text fields are constructed using a Reader. Lucene can read // and index very large chunks of text, without storing the // entire content verbatim in the index. In this example we // can just wrap the content string in a StringReader. doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED)); return doc; } /** * Searches for the given string in the "content" field */ private static void search(Searcher searcher, String queryString) throws ParseException, IOException { // Build a Query object //Query query = QueryParser.parse( QueryParser parser = new QueryParser("content", new StandardAnalyzer(Version.LUCENE_48)); Query query = parser.parse(queryString); int hitsPerPage = 10; // Search for the query TopScoreDocCollector collector = TopScoreDocCollector.create(5 * hitsPerPage, false); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; int hitCount = collector.getTotalHits(); System.out.println(hitCount + " total matching documents"); // Examine the Hits object to see if there were any matches if (hitCount == 0) { System.out.println( "No matches were found for \"" + queryString + "\""); } else { System.out.println("Hits for \"" + queryString + "\" were found in quotes by:"); // Iterate over the Documents in the Hits object for (int i = 0; i < hitCount; i++) { // Document doc = hits.doc(i); ScoreDoc scoreDoc = hits[i]; int docId = scoreDoc.doc; float docScore = scoreDoc.score; System.out.println("docId: " + docId + "\t" + "docScore: " + docScore); Document doc = searcher.doc(docId); // Print the value that we stored in the "title" field. Note // that this Field was not indexed, but (unlike the // "contents" field) was stored verbatim and can be // retrieved. System.out.println(" " + (i + 1) + ". " + doc.get("title")); System.out.println("Content: " + doc.get("content")); } } System.out.println(); } }
但它在以下几行中显示了一些语法错误:
错误一:
IndexWriter writer = 红色下划线 MaxFieldLength new IndexWriter(idx, new StandardAnalyzer(Version.LUCENE_48), IndexWriter.MaxFieldLength.LIMITED);
错误 2:在红色下划线 optimeze()
writer.optimize();
错误 3:用红色下划线 new IndexSearcher(idx)
搜索者 searcher = new IndexSearcher(idx);
错误4:红色下划线搜索
searcher.search(查询,收集器);
你能帮我摆脱这些错误吗?这将是一个很大的帮助。谢谢
修改后的代码:
公共类 InMemoryExample {
public static void main(String[] args) throws Exception{ // 构造一个 RAMDirectory 来保存索引的内存表示 //。RAMDirectory idx = new RAMDirectory();
// Make an writer to create the index IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_48, new
标准分析仪(版本.LUCENE_48));IndexWriter writer = new IndexWriter(idx, cfg);
// Add some Document objects containing quotes writer.addDocument(createDocument("Theodore Roosevelt", "It behooves every man to remember that the work of the " + "critic, is of altogether secondary importance, and that, " + "in the end, progress is accomplished by the man who does " + "things.")); writer.addDocument(createDocument("Friedrich Hayek", "The case for individual freedom rests largely on the " + "recognition of the inevitable and universal ignorance " + "of all of us concerning a great many of the factors on " + "which the achievements of our ends and welfare depend.")); writer.addDocument(createDocument("Ayn Rand", "There is nothing to take a man's freedom away from " + "him, save other men. To be free, a man must be free " + "of his brothers.")); writer.addDocument(createDocument("Mohandas Gandhi", "Freedom is not worth having if it does not connote " + "freedom to err.")); // Optimize and close the writer to finish building the index writer.commit(); writer.close(); // Build an IndexSearcher using the in-memory index IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(idx)); // Run some queries search(searcher, "freedom"); search(searcher, "free"); search(searcher, "progress or achievements"); //searcher.close(); } /** * Make a Document object with an un-indexed title field and an * indexed content field. */ private static Document createDocument(String title, String content) { Document doc = new Document(); // Add the title as an unindexed field... doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO)); // ...and the content as an indexed field. Note that indexed // Text fields are constructed using a Reader. Lucene can read // and index very large chunks of text, without storing the // entire content verbatim in the index. In this example we // can just wrap the content string in a StringReader. doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED)); return doc; } /** * Searches for the given string in the "content" field */ private static void search(IndexSearcher searcher, String queryString) throws ParseException, IOException { // Build a Query object //Query query = QueryParser.parse( QueryParser parser = new QueryParser("content", new StandardAnalyzer(Version.LUCENE_48)); Query query = parser.parse(queryString); int hitsPerPage = 10; // Search for the query TopScoreDocCollector collector = TopScoreDocCollector.create(5 * hitsPerPage, false); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; int hitCount = collector.getTotalHits(); System.out.println(hitCount + " total matching documents"); // Examine the Hits object to see if there were any matches if (hitCount == 0) { System.out.println( "No matches were found for \"" + queryString + "\""); } else { System.out.println("Hits for \"" + queryString + "\" were found in quotes by:"); // Iterate over the Documents in the Hits object for (int i = 0; i < hitCount; i++) { // Document doc = hits.doc(i); ScoreDoc scoreDoc = hits[i]; int docId = scoreDoc.doc; float docScore = scoreDoc.score; System.out.println("docId: " + docId + "\t" + "docScore: " + docScore); Document doc = searcher.doc(docId); // Print the value that we stored in the "title" field. Note // that this Field was not indexed, but (unlike the // "contents" field) was stored verbatim and can be // retrieved. System.out.println(" " + (i + 1) + ". " + doc.get("title")); System.out.println("Content: " + doc.get("content")); } } System.out.println(); } }
这是输出:
线程“主”java.lang.VerifyError 中的异常:类 org.apache.lucene.analysis.SimpleAnalyzer 覆盖最终方法 tokenStream.(Ljava/lang/String;Ljava/io/Reader;)Lorg/apache/lucene/analysis/TokenStream ; 在 java.lang.ClassLoader.defineClass1(Native Method) 在 java.lang.ClassLoader.defineClass(Unknown Source) 在 java.security.SecureClassLoader.defineClass(Unknown Source) 在 java.net.URLClassLoader.defineClass(Unknown Source) 在 java .net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader。