AccountSearchRepositorySolrj.java 2.28 KB
package org.legrog.entities;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.inject.Default;
import javax.inject.Inject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Implementation of AccountSearchRepository using SolrJ
 */
@Default
public class AccountSearchRepositorySolrj implements AccountSearchRepository {
    Logger logger = LoggerFactory.getLogger(getClass());

    SolrClient solrClient;

    protected static String collectionName = "accounts";

    @Inject
    AccountSearchRepositorySolrj(SolrClient solrClient) {
        this.solrClient = solrClient;
    }

    //no args constructor to make it proxyable
    AccountSearchRepositorySolrj() {
    }

    @Override
    public List<IndexedAccount> search(String string) throws SearchingException {
        SolrQuery solrQuery = new SolrQuery(string);
        QueryResponse queryResponse;
        try {
            queryResponse = solrClient.query(collectionName, solrQuery);
        } catch (IOException ioe) {
            throw new SearchingException(ioe);
        } catch (SolrServerException sse) {
            logger.error("SolrServerException {}", sse);
            throw new SearchingException(sse.getRootCause());
        }

        if (queryResponse != null) {
            return queryResponse.getBeans(IndexedAccount.class);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void reindex(List<IndexedAccount> indexedAccounts) throws IndexingException {
        try {
            UpdateResponse updateResponse = solrClient.addBeans(collectionName, indexedAccounts);
            solrClient.commit(collectionName);
            logger.trace("reindex indexedAccounts SolrJ UpdateResponse {}", updateResponse);
        } catch (IOException ioe) {
            throw new IndexingException(ioe);
        } catch (SolrServerException sse) {
            logger.error("SolrServerException {}", sse);
            throw new IndexingException(sse.getRootCause());
        }
    }
}