为什么Lucene没有找到这个代码的任何文件?

时间:2014-03-27 16:10:17

标签: java search full-text-search lucene

我正在处理这段代码,它将一个文档添加到lucene(4.7)索引中,然后通过查询文档中存在的术语来确定找到它。但indexSearcher不会返回任何文档。我的代码出了什么问题?感谢您的意见和反馈。

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

1 个答案:

答案 0 :(得分:2)

这是因为您使用StringField。来自javadoc:

  

索引但未标记化的字段:整个String值被索引为单个标记。

只需使用TextField代替就可以了。