drag drag - 10 months ago 60
Java Question

How to creat index and search query in Java Lucene 6.2.0

I want to use Lucene version 6.2.0, I created two functions in java is creatIndex and searchIndex but it doesn't run. I don't understand how to use Field to argument of Documents methods.

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);

Answer Source

Three problems strike me here:

  1. Your creatDocuments opens an index in the same place it's looking for files to index, at the Files argument. Your searchIndex method is then looking for the index at INDEX_DIRECTORY. I presume your creatDocuments should be opening a writer at INDEX_DIRECTORY as well. Like

    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()) {
  2. Your FieldType won't work. You need to at the very least specify that it is either indexed or stored. I would recommend you don't start with custom field types. Just use the Field implementations with pre-defined field types, like TextField (see the list of "Direct Known Subclasses" in the 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);
  3. You are reusing the same Document, rather than creating a new ones for each file. You should be constructing a new Document for each iteration of your for loop.