【问题标题】:Why doesn't Lucene find any documents with this code?为什么 Lucene 找不到包含此代码的任何文档?
【发布时间】:2014-05-06 18:08:33
【问题描述】:

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

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

【问题讨论】:

    标签: java search full-text-search lucene


    【解决方案1】:

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

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

    只需改用TextField 就可以了。

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2014-12-19
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 2016-05-18
      相关资源
      最近更新 更多