2014-03-27 31 views
0

我正在處理這段代碼,它將單個文檔添加到lucene(4.7)索引,然後嘗試通過查詢文檔中存在的術語來查找它。但是indexSearcher不會返回任何文檔。我的代碼有什麼問題?感謝您的意見和反饋。爲什麼不用Lucene找到這個代碼的任何文檔?

String indexDir = "/home/richard/luc_index_03"; 
    try { 
     Directory directory = new SimpleFSDirectory(new File(
       indexDir)); 
     Analyzer analyzer = new SimpleAnalyzer(
       Version.LUCENE_47); 
     IndexWriterConfig conf = new IndexWriterConfig(
       Version.LUCENE_47, analyzer); 
     conf.setOpenMode(OpenMode.CREATE_OR_APPEND); 
     conf.setRAMBufferSizeMB(256.0); 
     IndexWriter indexWriter = new IndexWriter(
       directory, conf); 

     Document doc = new Document(); 
     String title="New York is an awesome city to live!"; 
     doc.add(new StringField("title", title, StringField.Store.YES)); 
     indexWriter.addDocument(doc); 
     indexWriter.commit(); 
     indexWriter.close(); 
     directory.close(); 
     IndexReader reader = DirectoryReader 
       .open(FSDirectory.open(new File(
         indexDir))); 
     IndexSearcher indexSearcher = new IndexSearcher(
       reader); 


     String field="title"; 
     SimpleQueryParser qParser = new SimpleQueryParser(analyzer, field); 
     String queryText="New York" ; 
     Query query = qParser.parse(queryText); 
     int hitsPerPage = 100; 
     TopDocs results = indexSearcher.search(query, 5 * hitsPerPage); 
     System.out.println("number of results: "+results.totalHits); 
     ScoreDoc[] hits = results.scoreDocs; 
     int numTotalHits = results.totalHits; 

     for (ScoreDoc scoreDoc:hits){ 
      Document docC = indexSearcher.doc(scoreDoc.doc); 
      String path = docC.get("path"); 
      String titleC = docC.get("title"); 
      String ne = docC.get("ne"); 
      System.out.println(path+"\n"+titleC+"\n"+ne); 
      System.out.println("---*****----"); 

     } 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

運行我只是得到

number of results: 0 

回答

2

後這是因爲你用StringField。從javadoc:

索引但未標記化的字段:整個字符串值被索引爲單個標記。

只需使用TextField代替,您應該沒問題。

相關問題