java操作solr
<dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>8.1.0</version>
        </dependency>
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;

public class SolrClient {

    private volatile static SolrClient solrClient;
    private SolrClient(){}
    public static SolrClient getSolrClient(String url) {
        if (solrClient == null) {
            synchronized (MySolrClient.class) {
                if (solrClient == null) {
                    solrClient = new HttpSolrClient.Builder(url)
                            .withConnectionTimeout(10*1000)
                            .withSocketTimeout(30*1000)
                            .build();
                }
            }
        }
        return solrClient;
    }
}
/**
     * 添加或者更新solr库
     * 单条数据
     * @param document
     * @return
     */
    public static String addByDoc(SolrInputDocument document, String url) {
        SolrClient solrClient = MySolrClient.getSolrClient(url);
        String result = "success";
        try {
            solrClient.add(document);
            solrClient.commit();
            log.info("insert doc to solr success!");
        } catch (Exception e) {
            result = "failed";
            loggerErrToSolr(e);
        }
        return result;
    }

    /**
     * 添加或者更新solr库
     * 多条数据
     * @param docs
     * @return
     */
    public static String addByList(List<SolrInputDocument> docs, String url) {
        SolrClient solrClient = MySolrClient.getSolrClient(url);
        String result = "success";
        try {
            solrClient.add(docs);
            solrClient.commit();
            log.info("insert list to solr success!");
        } catch (Exception e) {
            result = "failed";
            loggerErrToSolr(e);
        }
        return result;
    }

如果是更新已经存在的记录里面的某个字段,可以这样实现:

 SolrInputDocument updateDocument = new SolrInputDocument();
            updateDocument.addField("FEATUREID", requestAddLayerElementDisable.getLayerName() + "_" + requestAddLayerElementDisable.getElement());//类似于id
            Map<String, Object> operationMap = new HashMap<String, Object>();
            operationMap.put("set", false);//要设置的值
            updateDocument.addField("VISIBLE", operationMap);//要更新的字段
            SolrUtil.addByDoc(updateDocument, jmsConfig.getSolrUrl());

 

posted on 2019-06-20 15:33  james-roger  阅读(186)  评论(0编辑  收藏  举报