-2

私はテキスト検索が初めてで、ルセンに関連するいくつかの例を研究しています。このリンクから例の1つを見つけました。http://javatechniques.com/blog/lucene-in-memory-text-search-example/ Eclipse IDE で試してみました。しかし、それはいくつかのエラーを与えます。関連するjarファイルもすべてインポートしました。

コードは次のとおりです。

public class 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();
   } }

ただし、次の行にいくつかの構文エラーが表示されます。

エラー 1:

IndexWriter writer = 赤で MaxFieldLength に下線を引く new IndexWriter(idx, new StandardAnalyzer(Version.LUCENE_48), IndexWriter.MaxFieldLength.LIMITED);

エラー 2: optimeze() に赤で下線を引く

ライター.optimize();

エラー 3: new IndexSearcher(idx) に赤で下線を引く

Searcher searcher = new IndexSearcher(idx);

エラー 4: 検索に赤で下線を引く

searcher.search(クエリ、コレクター);

これらのエラーを取り除くのを手伝ってもらえますか? とても助かります。ありがとう

変更されたコード:

public class InMemoryExample {

public static void main(String[] args) throws Exception{ // RAMDirectory を構築して、 // インデックスのインメモリ表現を保持します。RAMDirectory idx = 新しい RAMDirectory();

       // Make an writer to create the index
    IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_48, new

StandardAnalyzer(Version.LUCENE_48)); IndexWriter ライター = 新しい 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(ネイティブ メソッド)で java.lang.ClassLoader.defineClass(不明なソース)で java.security.SecureClassLoader.defineClass(不明なソース)で java.net.URLClassLoader.defineClass(不明なソース)で.net.URLClassLoader.access$100 (未知のソース) で java.net.URLClassLoader$1.run (未知のソース) で java.net.URLClassLoader$1.run (未知のソース) で java.security.AccessController.doPrivileged(Native Method) でjava.net.URLClassLoader.findClass(不明なソース) java.lang.ClassLoader.loadClass(不明なソース) で sun.misc.Launcher$AppClassLoader.

4

1 に答える 1

0

IndexWriterコンストラクターに 3 番目の引数がありません。次のように、新しい lucene API に合わせてコードを変更する必要があります。

IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_48, new StandardAnalyzer(Version.LUCENE_48));
IndexWriter writer = new IndexWriter(idx, cfg);

また、ここで例外をキャッチするのではなく、mainメソッドをスローExceptionさせて、プログラムを完全に失敗させたいと思います

編集 :

2)クラスにそのメソッドがなくなっoptimizeたため、呼び出しを削除します(ここでトリックを行うと思います)。IndexWritercommit

3)IndexSearcherクラスを次のように定義します。

IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(idx));
于 2014-06-25T12:11:58.447 に答える