如何使用lucene进行搜索

如何使用lucene进行搜索,lucene,Lucene,我想找到这个词“且试天下" .这是一个中文单词。 所以关键是“且试天下" 但是当我搜索时,结果包含三个这样的文档 且试天下 且共从容 梦之无游天下录 实际上,我只想得到第一个结果。只有第一个结果与键相同。第二个和第三个结果只是在键中包含一些单词 这是我的代码,我使用lucene 5.5 public void doSearch() throws Exception { String key = "且试天下"; Path path = FileSystems.get

我想找到这个词“且试天下" .这是一个中文单词。 所以关键是“且试天下"

但是当我搜索时,结果包含三个这样的文档

且试天下

共从容

梦之无游<强>天下

实际上,我只想得到第一个结果。只有第一个结果与键相同。第二个和第三个结果只是在键中包含一些单词

这是我的代码,我使用lucene 5.5

public void doSearch() throws Exception {
        String key = "且试天下";
        Path path = FileSystems.getDefault().getPath("D:/Lucene/StoryExercise", "index");
        Directory directory = new NIOFSDirectory(path);
        IndexReader ir = DirectoryReader.open(directory);
        IndexSearcher is = new IndexSearcher(ir);
        Analyzer analyzer = new SmartChineseAnalyzer();
        Builder builder = new BooleanQuery.Builder();
        QueryParser qp = new ComplexPhraseQueryParser("filename", analyzer);
        Query parse = qp.parse(key);
        builder.add(new BooleanClause(parse, BooleanClause.Occur.MUST));
        BooleanQuery build = builder.build();
        TopDocs td = is.search(build, 100);
        ScoreDoc[] docs = td.scoreDocs;
        Document doc = null;
        int i = 1;
        for (ScoreDoc sd : docs) {
            doc = is.doc(sd.doc);
            System.out.println(doc.get("filename") + "  HAS THE WORD : " + key + i++);
        }
    }
下面是构建索引的代码

public void doIndex() throws Exception {
        Path path = FileSystems.getDefault().getPath("D:/Lucene/StoryExercise", "index");
        Directory directory = new NIOFSDirectory(path);
        Analyzer analyzer = new SmartChineseAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        IndexWriter iw = new IndexWriter(directory, iwc);

        File filedir = new File("D:/Lucene/StoryExercise/data");
        Document doc = null;
        for (File file : filedir.listFiles()) {
            doc = new Document();
            doc.add(new TextField("path", file.getPath(), Field.Store.YES));
            doc.add(new TextField("filename", file.getName(), Field.Store.YES));
            doc.add(new TextField("content", new FileReader(file)));
            iw.addDocument(doc);
        }
        iw.close();
    }

分析器用于将字符串拆分为令牌。
SmartChineseAnalyzer
splits“且试天下“进入”且", "试“、和”天下,很像
StandardAnalyzer
将“谁得到世界”分为“谁”、“得到”和“世界”

如果您想作为短语进行搜索,您的查询应该被引用:
qp.parse(“\”且试天下\"");


如果不希望分析字段,请将其索引为
StringField
(或使用
KeywordAnalyzer
).

我真的很感谢你,你的回答太详细了。你能给我推荐一些书或博士来学习lucene吗。官方博士没有详细的知识,或者可能我找不到。或者。谢谢。@Vincent-你可以看看的入门部分,特别是。就一本书而言,是典型的推荐,但是请记住,那里的代码已经非常过时了(使用Lucene 3.0.1编写,当前版本为5.5.0,差异将非常显著)