2016-02-05 3 views
0

Я использую lucene 3 для индексации некоторого txt-файла, подобного этому.Почему индексатор не ищет персидские файлы?

public static void main(String[] args) throws Exception { 

    String indexDir = "file input"; 
    String dataDir = "file input"; 
    long start = System.currentTimeMillis(); 

    indexer indexer = new indexer(indexDir); 
    int numIndexed, cnt; 
    try { 
     numIndexed = indexer.index(dataDir, new TextFilesFilter()); 

     cnt = indexer.getHitCount("mycontents", "شهردار"); 
     System.out.println("count of search in contents: " + cnt); 
    } finally { 
     indexer.close(); 
    } 
    long end = System.currentTimeMillis(); 
    System.out.println("Indexing " + numIndexed + " files took " 
      + (end - start) + " milliseconds"); 

} 

Функция getHitCount возвращает количество обращений по английскому слову, но персидским словом, оно возвращает ноль!

public int getHitCount(String fieldName, String searchString) 
     throws IOException, ParseException { 

    IndexSearcher searcher = new IndexSearcher(directory); 

    Term t = new Term(fieldName, searchString); 
    Query query = new TermQuery(t); 

    int hitCount = searcher.search(query, 1).totalHits; 
    searcher.close(); 
    return hitCount; 
} 

Как установить utf-8 в мой проект? Я использую netbeans и создаю простой Java-проект. Мне просто нужен простой поиск в файлах!

Это мой индексатор класс:

private IndexWriter writer; 
private Directory directory; 

public indexer(String indexDir) throws IOException { 
    directory = FSDirectory.open(new File(indexDir)); 
    writer = new IndexWriter(directory, 
      new StandardAnalyzer(
        Version.LUCENE_30), 
      true, 
      IndexWriter.MaxFieldLength.UNLIMITED); 
} 

public void close() throws IOException { 
    writer.close(); 
} 

public int index(String dataDir, FileFilter filter) 
     throws Exception { 
    File[] files = new File(dataDir).listFiles(); 
    for (File f : files) { 
     if (!f.isDirectory() 
       && !f.isHidden() 
       && f.exists() 
       && f.canRead() 
       && (filter == null || filter.accept(f))) { 
      indexFile(f); 
     } 
    } 
    return writer.numDocs(); 
} 

private static class TextFilesFilter implements FileFilter { 

    public boolean accept(File path) { 
     return path.getName().toLowerCase() 
       .endsWith(".txt"); 
    } 
} 

protected Document getDocument(File f) throws Exception { 
    Document doc = new Document(); 
    doc.add(new Field("mycontents", new FileReader(f))); 
    doc.add(new Field("filename", f.getName(), 
      Field.Store.YES, Field.Index.NOT_ANALYZED)); 
    doc.add(new Field("fullpath", f.getCanonicalPath(), 
      Field.Store.YES, Field.Index.NOT_ANALYZED)); 
    return doc; 
} 

private void indexFile(File f) throws Exception { 
    System.out.println("Indexing " + f.getCanonicalPath()); 
    Document doc = getDocument(f); 
    writer.addDocument(doc); 
} 
+0

мы могли видеть ваш класс индексатор? Кажется, вы что-то внедрили. – Niklas

+0

@ Никлас Я редактировал мой вопрос. – NASRIN

+0

Это должно помочь вам: http://stackoverflow.com/questions/23030329/lucene-encoding-java – Niklas

ответ

0

Я подозреваю, что этот вопрос не является кодированием Lucene, в самом по себе, но FileReader. Из документов FileReader:

Конструкторы этого класса предполагают, что кодировка символов по умолчанию и размер байта по умолчанию являются подходящими.

Кодировка символов по умолчанию, вероятно, не подходит, в данном случае.

Вместо:

doc.add(new Field("mycontents", new FileReader(f))); 

попытки (предполагается, что файл будет индексироваться в UTF-8 закодированы):

doc.add(new Field("mycontents", new InputStreamReader(new FileInputStream(f), "UTF8"))); 
Смежные вопросы