我想使用Lucene 6.2.0版,我在java中创建了两个函数是creatIndex和searchIndex,但是它没有运行。我不明白如何使用Field来描述Documents方法。
public void searchIndex(String sentence) throws IOException
{
File dir = new File(INDEX_DIRECTORY);
Path path = dir.toPath();
Directory directory = FSDirectory.open(path);
DirectoryReader ireader=DirectoryReader.open(directory);
IndexSearcher isearcher=new IndexSearcher(ireader);
PhraseQuery.Builder builder = new PhraseQuery.Builder();
String[] words = sentence.split(" ");
for (String word : words) {
builder.add(new Term("contents", word));
}
PhraseQuery pq = builder.build();
TopDocs topDocs = isearcher.search(pq, 10);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document doc = isearcher.doc(scoreDoc.doc);
System.out.println(doc);
}
}
答案 0 :(得分:0)
这里有三个问题:
您的creatDocuments
会在Files
参数的同一位置打开索引以查找要索引的文件。然后,您的searchIndex
方法会在INDEX_DIRECTORY
处查找索引。我认为你的creatDocuments
也应该在INDEX_DIRECTORY
打开作家。像
FSDirectory luceneDirectory = FSDirectory.open(new File(INDEX_DIRECTORY).toPath());
IndexWriterConfig conf = new IndexWriterConfig();
try (IndexWriter indexWriter = new IndexWriter(directory, conf)) {
for (File file : new File(Files).listFiles()) {
...
您的FieldType
将无效。您至少需要 指定它被索引或存储。我建议你不要从自定义字段类型开始。只需将Field
实现与预定义的字段类型一起使用,例如TextField
(请参阅Field documentation中的“直接已知子类”列表。)
Field contentField = new TextField(LuceneConstants.CONTENTS, reader);
Field fileNameField = new TextField(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES);
Field filePathField = new TextField(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.NO);
您正在重复使用相同的Document
,而不是为每个文件创建新的Document
。您应该为for循环的每次迭代构建一个新的 <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<ProduceOutputsOnBuild>True</ProduceOutputsOnBuild>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<ProduceOutputsOnBuild>True</ProduceOutputsOnBuild>
</PropertyGroup>
。