Индекс Lucene: отсутствующие документы

У нас есть довольно простая настройка Lucene. Недавно мы заметили, что некоторые документы не записываются в индекс.

Вот как мы создаем документ:

private void addToDirectory(SpecialDomainObject specialDomainObject) throws IOException     {
    Document document = new Document();
    document.add(new TextField("id", String.valueOf(specialDomainObject.getId()), Field.Store.YES));
    document.add(new TextField("name", specialDomainObject.getName(), Field.Store.YES));
    document.add(new TextField("tags", joinTags(specialDomainObject.getTags()), Field.Store.YES));
    document.add(new TextField("contents", getContents(specialDomainObject), Field.Store.YES));

    for (Language language : getAllAssociatedLanguages(specialDomainObject)) {
        document.add(new IntField("languageId", language.getId(), Field.Store.YES));
    }
    specialDomainObjectIndexWriter.updateDocument(new Term("id", document.getField("id").stringValue()), document);
    specialDomainObjectIndexWriter.commit();
}

Вот как мы создаем анализатор и составитель индекса:

<bean id="luceneVersion" class="org.apache.lucene.util.Version" factory-method="valueOf">
    <constructor-arg value="LUCENE_46"/>
</bean>

<bean id="analyzer" class="org.apache.lucene.analysis.standard.StandardAnalyzer">
    <constructor-arg ref="luceneVersion"/>
</bean>

<bean id="specialDomainObjectIndexWriter" class="org.apache.lucene.index.IndexWriter">
    <constructor-arg ref="specialDomainObjectDirectory" />
    <constructor-arg>
        <bean class="org.apache.lucene.index.IndexWriterConfig">
            <constructor-arg ref="luceneVersion"/>
            <constructor-arg ref="analyzer" />
            <property name="openMode" value="CREATE_OR_APPEND"/>
        </bean>
    </constructor-arg>
</bean>

Индексирование выполняется с помощью запланированной задачи:

@Component
public class ScheduledSpecialDomainObjectIndexCreationTask implements ScheduledIndexCreationTask {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledSpecialDomainObjectIndexCreationTask.class);

    @Autowired
    private IndexOperator specialDomainObjectIndexOperator;

    @Scheduled(fixedDelay = 3600 * 1000)
    @Override
    public void createIndex() {
        Date indexCreationStartDate = new Date();
        try {
            logger.info("Updating complete special domain object index...");
            specialDomainObjectIndexOperator.createIndex();
            if (logger.isDebugEnabled()) {
                Date indexCreationEndDate = new Date();
                logger.debug("Index creation duration: {} ms", indexCreationEndDate.getTime() - indexCreationStartDate.getTime());
            }
        } catch (IOException e) {
            logger.error("Could update complete special domain object index.", e);
        }
    }
}

createIndex () реализован следующим образом:

@Override
public void createIndex() throws IOException {
    logger.trace("Preparing for index generation...");
    IndexWriter indexWriter = getIndexWriter();

    Date start = new Date();

    logger.trace("Deleting all documents from index...");
    indexWriter.deleteAll();

    logger.trace("Starting index generation...");
    long numberOfProcessedObjects = fillIndex();

    logger.debug("Index written in " + (new Date().getTime() - start.getTime()) + " milliseconds.");
    logger.debug("Number of processed objects: {}", numberOfProcessedObjects);
    logger.debug("Number of documents in index: {}", indexWriter.numDocs());

    indexWriter.commit();
    indexWriter.forceMerge(1);
}

@Override
protected long fillIndex() throws IOException {
    Page<SpecialDomainObject> specialDomainObjectsPage = specialDomainObjectRepository.findAll(new PageRequest(0, MAXIMUM_PAGE_ELEMENTS));
    while (true) {
        addToDirectory(specialDomainObjectsPage);
        if (specialDomainObjectsPage.hasNextPage()) {
            specialDomainObjectsPage =
                specialDomainObjectRepository.findAll(new PageRequest(specialDomainObjectsPage.getNumber() + 1, specialDomainObjectsPage.getSize()));
        } else {
            break;
        }
    }
    return specialDomainObjectsPage.getTotalElements();
}

Существует около 2000 экземпляров specialDomainObject, и около 80 не записываются в индекс (мы проверили это с помощью Люка).

Есть ли что-нибудь, что могло стать причиной пропажи документов?


person Alexander Müller    schedule 31.01.2014    source источник
comment
Я должен спросить. Вы изящно закрываете IndexWriter, не так ли?   -  person Martín Schonaker    schedule 02.02.2014
comment
Да, мы. Мы определили проблему.   -  person Alexander Müller    schedule 03.04.2014


Ответы (1)


Мы обнаружили проблему: кодировка операционной системы по умолчанию не была установлена ​​на UTF-8.

person Alexander Müller    schedule 03.04.2014