0
votes

I use Lucene library for search, and when I update info in objects which I search I need reindex this object. So I do following:

    IndexWriterConfig config = new IndexWriterConfig(OffersSearchEJB.VERSION, OffersSearchEJB.ANALYZER);
    config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    config.setRAMBufferSizeMB(64);
    config.setMaxBufferedDocs(2000);

    IndexWriter indexWriter;
    try {
        indexWriter = new IndexWriter(OffersSearchEJB.DIRECTORY, config);
        Document doc = new Document();
        IntField idField = new IntField("id", 0, Field.Store.YES);
        TextField shortTitleField = new TextField("shortTitle", "", Field.Store.NO);
        TextField titleField = new TextField("title", "", Field.Store.NO);
        TextField termsField = new TextField("terms", "", Field.Store.NO);
        TextField featuresField = new TextField("features", "", Field.Store.NO);
        TextField descriptionField = new TextField("description", "", Field.Store.NO);
        // deleting old index
        Term term = new Term("id", offer.getId().toString());
        indexWriter.deleteDocuments(term);
        // storing new index
        OffersSearchEJB.indexOffer(offer, indexWriter, doc, idField, shortTitleField, titleField, termsField, featuresField, descriptionField);
        indexWriter.commit();
        indexWriter.close();
    } catch (IOException ex) {
        Logger.getLogger(OfferMDB.class.getName()).log(Level.SEVERE, null, ex);
    }

In other words, I just add new Object and delete old. Adding new object to index works good, but this code is not deleting old index. Also I tried indexWriter.updateDocument(term, doc);

I use Lucene 4.7, JDK 1.6 with Jboss 6.4

1

1 Answers

2
votes

This isn't working because your ID is an IntField, so it is encoded, not indexed as a simple term.

Two good solutions here:

  1. Change your idField to a StringField. If your id is just used as an identifier, I would definitely recommend this. Even though the field may be made up of digits, if you don't treat it like a number (such as using range queries, or sorting on it), then don't index it as a number.

  2. Use a numeric query, instead of a term, to delete the documents, something like:

    Query query = NumericRangeQuery.newIntRange("id", offer.getId(), offer.getId(), true, true);
    indexWriter.deleteDocuments(query);