2016-05-09 3 views
0

Когда я использовал веб-приложение carrot2, кластерное своими данными с индексом lucene, я обнаружил, что результат не совпадает с моим ожидаемым.Как я могу развернуть веб-приложение carrot2, разбирая свои собственные данные с индексом lucene?

error one: [В списке результатов справа перечислены только имя файла кластера без соответствующих текстовых проходов и местоположений файлов, я не уверен, что вызвало проблему, возможно, когда я использую lucene для создания формат индексного файла неправильный, или мой проект веб-приложения carrot2 конфигурации есть проблема, я надеюсь, что кто-то может сказать мне ответ] [извините, я не могу по моему картине для этого, вы можете посмотреть картинку по ошибке два .]

ошибка два: I found my search results showed that "other topics" not only a specific topic, it bothers me. I think there might be a problem clustering algorithm or is the topic of test data I have provided too little reason.

When I use the K-means clustering algorithm, the results came out a lot of topics, but no specific topic name but only the file name.

Если кто-то может ответить на мои сомнения, я был бы очень признателен, и ваш ответ будет полезен.

это мой код для создания индекса Lucene файлов:

package test2; 

import org.apache.lucene.index.IndexFileNames; 
import org.apache.lucene.index.IndexWriter; 
import org.apache.lucene.index.IndexWriterConfig; 
import org.apache.lucene.index.IndexWriterConfig.OpenMode; 
import org.apache.lucene.analysis.Analyzer; 
import org.apache.lucene.analysis.standard.StandardAnalyzer; 
import org.apache.lucene.document.Document; 
import org.apache.lucene.document.Field; 
import org.apache.lucene.document.LongField; 
import org.apache.lucene.document.StringField; 
import org.apache.lucene.document.TextField; 
import org.apache.lucene.store.FSDirectory; 
import org.apache.lucene.store.Directory; 
import org.apache.lucene.util.Version; 
import org.carrot2.source.lucene.SimpleFieldMapper; 

import java.io.File; 
import java.io.FileFilter; 
import java.io.IOException; 
import java.io.FileReader; 


//lucene 4.9 
public class LuceneDemo2 { 
    public static void main(String[] args) throws Exception { 
     String indexDir = "D:\\data\\lucene\\odp\\index-all"; 
     String dataDir = "D:\\data"; 

     long start = System.currentTimeMillis(); 
     LuceneDemo2 indexer = new LuceneDemo2(indexDir); 

     int numIndexed; 
     try { 
      numIndexed = indexer.index(dataDir,new TextFilesFilter()); 
     } finally { 
      indexer.close(); 
     } 
     long end = System.currentTimeMillis(); 

     System.out.println("Indexing " + numIndexed + " files took " + (end-start) + " milliseconds."); 
    } 

    private IndexWriter writer; 

    public LuceneDemo2(String indexDir) throws IOException { 
     // TODO Auto-generated constructor stub 
     Directory directory = FSDirectory.open(new File(indexDir)); 
     Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_9); 
     IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9,analyzer); 
     config.setOpenMode(OpenMode.CREATE); 
     writer = new IndexWriter(directory,config); 
    } 

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

    public int index (String dataDir,FileFilter filter) throws Exception { 
     File[] files = new File(dataDir).listFiles(); 

     //if(files == null) return writer.numDocs(); 
     for(File f: files) { 
      if(!f.isDirectory()&& 
       !f.isHidden()&& 
       f.exists()&& 
       f.canRead()&& 
       (filter == null || filter.accept(f))) { 
       indexFile(f); 
      } 
     } 

     /* 
     if(files == null) return writer.numDocs(); 
     for(int i=0;i<files.length&&files!=null;i++) { 
      if(!files[i].isDirectory()&& 
       !files[i].isHidden()&& 
       files[i].exists()&& 
       files[i].canRead()&& 
       (filter == null || filter.accept(files[i]))) { 
       indexFile(files[i]); 
      } 
     } 
     */ 
     return writer.numDocs(); 
    } 

    private static class TextFilesFilter implements FileFilter { 
     public boolean accept(File path) { 
      return path.getName().toLowerCase().endsWith(".txt"); 
     } 
    } 

    private Document getDocument(File f) throws Exception { 
     // TODO Auto-generated method stub 
     Document document = new Document(); 
     document.add(new StringField("path", f.getAbsolutePath(), Field.Store.YES)); 
     document.add(new LongField("modified", f.lastModified(), Field.Store.NO)); 
     document.add(new TextField("content", new FileReader(f))); 
     document.add(new TextField("title", f.getName(), Field.Store.YES)); 

     return document; 
    } 

    private void indexFile(File f) throws Exception { 
     // TODO Auto-generated method stub 
     System.out.println("Indexing "+ f.getCanonicalPath()); 
     Document document = getDocument(f); 
     writer.addDocument(document); 
    } 
} 

, что мой индексации PDF файлов кода (его часть):

private void indexFile(File f) throws Exception { 
     // TODO Auto-generated method stub 
     System.out.println("Indexing "+ f.getCanonicalPath()); 
     //Document d = LucenePDFDocument.getDocument(f); 
     String executeStr = "D:\\xpdf\\xpdfbin-win-3.04\\bin64\\pdftotext.exe"; 
     String[] cmd = new String[]{executeStr,"-enc","UTF-8","-q",f.getAbsolutePath(),"-"}; 
     String str = null ; 
     Process p = null ;  
     BufferedReader br = null ; 
     StringBuffer sb = new StringBuffer() ; 
     try { 
      p = Runtime.getRuntime().exec(cmd) ;    
      br = new BufferedReader(new InputStreamReader(p.getInputStream(),"UTF-8")) ;  
      while((str = br.readLine()) != null){ 
       sb.append(str).append("\n") ; 
      }    
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally{ 
      if (br != null){ 
       try { 
        br.close() ; 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
     String content = sb.toString(); 
     Document document = new Document(); 
     document.add(new StringField("url", f.getAbsolutePath(), Store.YES)); 
     document.add(new TextField("content", content,Store.YES)); 
     document.add(new TextField("title", f.getName(), Store.YES)); 
     writer.addDocument(document); 
    } 
+0

Сегодня я нахожу ошибку, меняя document.add (новый StringField («путь», f.getAbsolutePath(), Field.Store.YES)); - document.add (новый StringField ("url", f.getAbsolutePath(), Field.Store.YES)); –

ответ

1

Carrot2 алгоритмы работают на необработанный текст документов , поэтому необходимо сохранить все поля содержимого, которые вы хотите скопировать (Field.Store.YES). Чтобы ваше поле содержимого содержалось в индексе, самым простым решением было бы прочитать содержимое соответствующего файла в String, а затем использовать String-based constructor класса TextField.

После того, как вы переопределите свой контент и установите Carrot2 в кластер на основе полей «title» и «content», вы должны увидеть некоторые значимые кластеры.

+0

Благодарим за терпение, я думаю, что уже знаю, где проблема выше. Но теперь я встретил еще один тернистый вопрос, хотел бы услышать ваше мнение. –

+0

Мне в настоящее время нужно создать индекс в большом количестве PDF-файлов, но когда я использую XPDF для чтения моих PDF-файлов и создания полей содержимого «content», я нахожу, что поле «content» отображает бессмысленные цифры, а не допустимое поле (Кстати, я использую программное обеспечение «luke» для просмотра), я много раз пробовал, но все как этот результат, я хотел бы знать, почему. Вероятно, потому, что PDF не читается простым текстом, поэтому есть проблема, но после того, как я конвертирую PDF непосредственно в TXT, а затем прочитайте TXT, у вас еще есть эта проблема. Переходим к вашему ответу. –