2012-05-05 6 views
12

Soy nuevo en Java y Lucene. Mi código obtiene una línea de un archivo y la almacena en el índice Lucene. Pero cuando creo un IndexReader para buscar y leer desde el índice arroja una excepción.org.apache.lucene.index.IndexNotFoundException: ningún segmento * archivo encontrado en org.apache.lucene.store.RAMDirectory

Mi código de Java está debajo. En la creación de la IndexReader lanza una IndexNotFoundException

static String itemsfreq[]; 
static StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); 
static IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer); 

public static void index_data(Directory indexed_document,int doc_num,IndexWriter w) throws IOException 
    { 
    for(int i = 0;i < itemsfreq.length;i++) 
     { 
     Document doc = new Document(); 
     doc.add(new Field(Integer.toString(doc_num)+","+itemsfreq[i],itemsfreq[i++], Field.Store.YES, Field.Index.ANALYZED)); 
     w.addDocument(doc); 
     } 
    } 
//Gets string from a file and insert it in INDEX named indexed_document 
public static void main(String[] args) throws IOException 
    { 
    BufferedReader reader = new BufferedReader(new FileReader("fullText100.txt")); 
    String line; 
    int i = 0; 
    Directory indexed_document = new RAMDirectory(); 
    IndexWriter writer = new IndexWriter(indexed_document, config); 
    while((line=reader.readLine()) != null) 
     { 
     if(i == 1) 
      { 
      break; 
      } 
     itemsfreq = line.split(" "); 
     index_data(indexed_document,i,writer); 
     i++; 
     } 

    IndexReader r = IndexReader.open(indexed_document); 
    } 

Respuesta

14

Con el fin de escribir los cambios en el índice hay que cerrar el escritor índice y luego abrir el IndexReader.

writer.close(); 

Si tiene que abrir la IndexReader antes de que se complete la escritura, hay que decir la IndexReader reabrir el índice con el fin de ver los cambios.

+0

He aplicado esta solución y funcionó. –

16

antes de abrir el índice utilizando un lector, llamada una vez writer.commit()

+1

Me enfrentaba un problema similar, y el uso de 'writer.commit()' lo solucionó. Si hubiera usado 'writer.close()', tendría que volver a abrir el escritor nuevamente. Tu sugerencia es mejor que la anterior. – tuxdna

+2

De hecho, esta es la solución correcta, ya que los documentos de Lucene recomiendan reutilizar instancias individuales de IndexWriter e IndexReader; De esta manera, no estoy obligado a cerrar el escritor y crearlo de nuevo cuando sea necesario. – Serg

3

Que tiene que hacer es llamar explícitamente a cometer antes de abrir su IndexSearcher.

directory = new RAMDirectory(); 
    iwriter = new IndexWriter(directory, config); 
    iwriter.commit(); 

ahora abierto Buscador

ireader = DirectoryReader.open(directory); 
isearcher = new IndexSearcher(ireader); 

Asimismo, recuerda que necesite llamar cometen después de añadir los documentos de lo contrario la búsqueda pueden no encontrarlo. Searcher necesita volver a abrir después de la confirmación (por supuesto, cerrar buscador antiguo).

iwriter.commit(); 
0

Tengo este error (en Lucene.Net, C#) porque había creado un índice mediante la creación del directorio apropiado en mi sistema de ficheros y FSDirectory en la memoria, pero en realidad no había añadido ningún documento todavía.

Específicamente, el código para agregar documentos nuevos se estaba comprobando para asegurarse de que no estaba agregando un duplicado con un lector, pero la excepción se produjo al intentar agregar el primer documento, porque todavía no había segmentos.

que se ocupó de este modo:

// Make a reader to check the index for duplicates 
// The reader will only be aware of items that were in the index before it was created 
IndexReader reader = null; 
try { 
    reader = IndexReader.Open(index, true); 
} catch(IOException) { 
    // There is no segments file because the index is empty 
    reader = null; 
} 

... // inside a method called by that scope, with reader passed in 

// See if it exists already 
// If the reader is null, then the index is empty 
if(reader != null) { 
    var existsTerm = new Term(SingleFieldIndexManager.FieldName, formattedTerm); 
    var matches = reader.TermDocs(existsTerm); 
    if(matches.Next()) { 
     // It's already in there, no need to add again 
     return; 
    } 
} 

... // back to the first method after a return 

// dispose of the reader if we managed to create one 
if(reader != null) { 
    reader.Dispose(); 
} 
+0

Oye, estoy teniendo el mismo problema que tú. Pero no entiendo cómo lo resolvió. Si no hay archivos, entonces ingresa al bloque catch y eso es todo, ¿verdad? – Valentin

+0

Encontrado el problema. Obtuve este error al crear IndexWriter con el parámetro create = false – Valentin

Cuestiones relacionadas