io.github.msurdi.redeye.core.lucene.QueryIndex.java Source code

Java tutorial

Introduction

Here is the source code for io.github.msurdi.redeye.core.lucene.QueryIndex.java

Source

/*******************************************************************************
 * Copyright 2013 Matias Surdi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package io.github.msurdi.redeye.core.lucene;

import io.github.msurdi.redeye.api.Indexable;
import io.github.msurdi.redeye.api.Query;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.SimpleFSDirectory;

import java.io.File;
import java.io.IOException;

/**
 * Implementation of an lucene for {@link io.github.msurdi.redeye.api.Query} instances.
 */
public class QueryIndex extends AbstractIndex<Query> {
    private static final String NAME_FIELD = "name";
    private static final String QUERY_FIELD = "query";
    private static final String DESCRIPTION_FIELD = "description";

    public QueryIndex() {
        super(new RAMDirectory());
    }

    public QueryIndex(File path) throws IOException {
        super(new SimpleFSDirectory(path));
    }

    @Override
    protected Query buildEntity(Document document) {
        return Query.builder().id(document.get(Indexable.ID_FIELD)).name(document.get(NAME_FIELD))
                .query(document.get(QUERY_FIELD)).description(document.get(DESCRIPTION_FIELD)).build();
    }

    @Override
    protected Document buildDocument(String id, Query query) {
        Document doc = new Document();
        doc.add(new StringField(Indexable.ID_FIELD, id, Field.Store.YES));
        doc.add(new TextField(NAME_FIELD, query.getName(), Field.Store.YES));
        doc.add(new StringField(QUERY_FIELD, query.getQuery(), Field.Store.YES));
        doc.add(new TextField(DESCRIPTION_FIELD, query.getDescription(), Field.Store.YES));
        return doc;
    }

}