java对solr的增删改查

1.在浏览器中删除solr数据
solr->document
在这里插入图片描述
2.增删改查
pom文件

 <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>7.7.3</version>
        </dependency>

代码:
AbsSolr:

package com.fdzy.solr.client;

import com.fdzy.client.entity.PhoneEntity;
import com.fdzy.client.entity.SearPage;
import com.fdzy.client.entity.SearResp;
import com.fdzy.solr.client.entity.PhoneSchema;
import com.fdzy.solr.client.query.SolrQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;
import org.modelmapper.ModelMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class AbsSolr {

    protected HttpSolrClient solr;

    public AbsSolr(String solrUrl) {
        solr = new HttpSolrClient.Builder(solrUrl).withConnectionTimeout(10000).withSocketTimeout(60000).build();
    }
    public void addField(String field, Integer value, SolrInputDocument document) {
        if (value != null) {
            document.addField(field, value);
        }
    }
    public void addField(String field, String value, SolrInputDocument document) {
        if (!StringUtils.isEmpty(value)) {
            document.addField(field, value);
        }
    }
    public void addField(String field, List<String> value, SolrInputDocument document) {
        if (value != null && value.size() != 0) {
            document.addField(field, value);
        }
    }
    public SolrInputDocument buildSolrDoc(PhoneEntity phoneEntity) {
        SolrInputDocument document = new SolrInputDocument();
        addField("phone", phoneEntity.getPhone(), document);
        addField("underPrice", phoneEntity.getUnderPrice(), document);
        addField("price", phoneEntity.getPrice(), document);
        addField("province", phoneEntity.getProvince(), document);
        addField("city", phoneEntity.getCity(), document);
        addField("operators", phoneEntity.getOperators(), document);
        addField("details", phoneEntity.getDetails(), document);
        addField("supplier", phoneEntity.getSupplier(), document);
        addField("addTime", phoneEntity.getAddTime(), document);
        addField("remake", phoneEntity.getRemake(), document);
        addField("status", 0, document);
        addField("midLabel", phoneEntity.getMidLabel(), document);
        addField("taillabel", phoneEntity.getTaillabel(), document);
        return document;
    }
    public void addFieldMap(String field, String value, SolrInputDocument document) {
        if (!StringUtils.isEmpty(value)) {
            Map<String,Object> phoneMap = new HashMap<>();
            phoneMap.put("set", value);
            document.addField(field, phoneMap);
        }
    }
    public void addFieldMap(String field, Integer value, SolrInputDocument document) {
        if (value != null) {
            Map<String,Object> phoneMap = new HashMap<>();
            phoneMap.put("set", value);
            document.addField(field, phoneMap);
        }
    }

    public SolrInputDocument buildSolrDocForUpdate(PhoneEntity phoneEntity) {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id", phoneEntity.getId());
        addFieldMap("phone", phoneEntity.getPhone(), document);
        addFieldMap("underPrice", phoneEntity.getUnderPrice(), document);
        addFieldMap("price", phoneEntity.getPrice(), document);
        addFieldMap("province", phoneEntity.getProvince(), document);
        addFieldMap("city", phoneEntity.getCity(), document);
        addFieldMap("operators", phoneEntity.getOperators(), document);
        addFieldMap("details", phoneEntity.getDetails(), document);
        addFieldMap("supplier", phoneEntity.getSupplier(), document);
        addFieldMap("addTime", phoneEntity.getAddTime(), document);
        addFieldMap("remake", phoneEntity.getRemake(), document);
        addFieldMap("status", phoneEntity.getStatus(), document);
        return document;
    }

    public SolrQuery getQuery(SearPage searPage) {
        SolrQuery query = new SolrQuery();

        StringBuffer sb = new StringBuffer();
        SolrQueryWrapper solrQueryWrapper = new SolrQueryWrapper();

        solrQueryWrapper.wrapperString(PhoneEntity.PROVINCE, searPage.getProvince(), sb)
                .wrapperString(PhoneEntity.CITY, searPage.getCity(), sb)
                .wrapperString(PhoneEntity.OPERATORS, searPage.getOperators(), sb)
                .wrapperRange(PhoneEntity.PRICE, searPage.getMinPrice(), searPage.getMaxPrice(), sb)
                .wrapperRange(PhoneEntity.ADDTIME, searPage.getMinAddTime(), searPage.getMaxAddTime(), sb)
                .wrapperString(
                        searPage.getRegularType() == null ? PhoneEntity.MIDLABEL :
                                searPage.getRegularType() == 0 ? PhoneEntity.MIDLABEL : PhoneEntity.TAILLABEL,
                        searPage.getRegular(), sb)
                .wrapperString(PhoneEntity.STATUS, searPage.getStatus() == null ? "" : searPage.getStatus() + "", sb)
                .wrapperString(PhoneEntity.SUPPLIER, searPage.getSupplier(), sb)
                .wrapperVague(PhoneEntity.PHONE, searPage.getVagueType(), searPage.getVagueText(), sb)
                .wrapperExact(PhoneEntity.PHONE, searPage.getExactText(), sb)
                .wrapperAny(PhoneEntity.PHONE, searPage.getAnyText(), sb)
                .wrapperInclude(PhoneEntity.PHONE, searPage.getIncludeNums(), sb)
        ;


        //设置分页参数
        if (sb.length() == 0)
            query.set("q", "*:*");
        else
            query.set("q", sb.toString());

        if (!StringUtils.isEmpty(searPage.getOrderField())) {
            // todo 多个字段排序price desc,phone desc,目前只是单个
            if (searPage.getOrder().equalsIgnoreCase("desc"))
                query.addSort(searPage.getOrderField(),  SolrQuery.ORDER.desc);
            else
                query.addSort(searPage.getOrderField(),  SolrQuery.ORDER.asc);
        }
        query.setStart(searPage.getStart());
        query.setRows(searPage.getSize());
        return query;
    }

    public PhoneEntity queryOne(String field, String value) {
        QueryResponse response = searchResponse(field + ":" + value, 0, 1);
        return getEntity(response).get(0);
    }

    protected QueryResponse searchResponse(String queryStr, Integer start, Integer size) {
        SolrQuery query =  new SolrQuery();
        query.setStart(start);
        query.setRows(size);
        query.set("q", queryStr);
        try {
            QueryResponse response = solr.query(query);
            return response;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected List<PhoneEntity> getEntity(QueryResponse response) {
        List<PhoneSchema> phoneSchemas = response.getBeans(PhoneSchema.class);
        List<PhoneEntity> phoneEntities = phoneSchemas.stream().map(e -> {
            PhoneEntity phoneEntity = new PhoneEntity();
            new ModelMapper().map(e,phoneEntity);
            return phoneEntity;
        }).collect(Collectors.toList());
        return phoneEntities;
    }

    protected SearResp searchQuery(String queryStr, Integer start, Integer size) {
        QueryResponse response = searchResponse(queryStr, start, size);
        SearResp searResp = new SearResp(start, size, response.getResults().getNumFound());
        searResp.setData(getEntity(response));
        return searResp;
    }
    /*
    SolrQuery query = new SolrQuery(); //下面设置solr查询参数
        //query.set("q", "*:*");// 参数q  查询所有
        query.set("q", "钢铁侠");//相关查询,比如某条数据某个字段含有周、星、驰三个字  将会查询出来 ,这个作用适用于联想查询
        //参数fq, 给query增加过滤查询条件
        query.addFacetQuery("id:[0 TO 9]");
        query.addFilterQuery("description:一个逗比的码农");
        query.set("df", "name");//参数df,给query设置默认搜索域,从哪个字段上查找
        query.setSort("id",SolrQuery.ORDER.desc);//参数sort,设置返回结果的排序规则
        //设置分页参数
        query.setStart(0);
        query.setRows(10);
        //设置高亮显示以及结果的样式
        query.setHighlight(true);
        query.addHighlightField("name");
        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");

     */
}

SolrClient:

package com.fdzy.solr.client;

import com.fdzy.client.api.ClientApi;
import com.fdzy.client.entity.PhoneEntity;
import com.fdzy.client.entity.SearPage;
import com.fdzy.client.entity.SearResp;
import com.fdzy.solr.client.entity.PhoneSchema;
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.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SolrClient extends AbsSolr implements ClientApi {

    private static SolrClient solrClient;
    private static final String REQUEST_HANDLER = "/suggest";

    public static SolrClient create(String solrUrl) {
        if (solrClient == null) {
            synchronized (SolrClient.class) {
                if (solrClient == null) {
                    solrClient = new SolrClient(solrUrl);
                }
            }
        }
        return solrClient;
    }

    private SolrClient(String solrUrl) {
        super(solrUrl);
    }
    @Override
    public void update(PhoneEntity phoneEntity) {
        SolrInputDocument doc = buildSolrDocForUpdate(phoneEntity);
        try {
            solr.add(doc);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateAddressByPhone(String phone, String province, String city) {
        // 查询
        QueryResponse response = searchResponse("phone:" + phone + "*", 0, 9999);
        List<PhoneSchema> phoneSchemas = response.getBeans(PhoneSchema.class);
        // 修改
        List<SolrInputDocument> list = new ArrayList<>();
        phoneSchemas.stream().forEach(e -> {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", e.getId());
            Map<String, String> provinceMap = new HashMap<>();
            provinceMap.put("set", province);
            document.addField("province", provinceMap);
            Map<String, String> cityMap = new HashMap<>();
            cityMap.put("set", city);
            document.addField("city", cityMap);
            list.add(document);
        });

        try {
            solr.add(list);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateOperatorsByPhone(String phone, String operators) {
        QueryResponse response = searchResponse("phone:" + phone + "* AND -(operators:*)", 0, 99999999);
        List<PhoneSchema> phoneSchemas = response.getBeans(PhoneSchema.class);
        List<SolrInputDocument> list = new ArrayList<>();
        phoneSchemas.stream().forEach(e -> {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", e.getId());
            Map<String, String> operatorsMap = new HashMap<>();
            operatorsMap.put("set", operators);
            document.addField("operators", operatorsMap);
            list.add(document);
        });

        try {
            solr.add(list);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            solr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public List<String> getSuggest(String query) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setRequestHandler(REQUEST_HANDLER);
        solrQuery.set("q", "remake:" + query);
        solrQuery.set("spellcheck.build", true);
        solrQuery.set("spellcheck", "on");

        QueryResponse response = null;
        try {
            response = solr.query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String> rtn = new ArrayList<>();
        if (response != null) {
            /*this._status = response.getStatus();
            this._QTime = response.getQTime();*/

            NamedList<Object> result = response.getResponse();
            NamedList map = (NamedList) result.get("spellcheck");
            if (map == null)
                return new ArrayList<>();
            NamedList nvPairs = (NamedList) map.get("suggestions");
            if (nvPairs == null)
                return new ArrayList<>();
            NamedList map2 = (NamedList) nvPairs.get(query);

            // this._count = Integer.parseInt(nvPairs.get("numFound").toString());
            if (map2 == null) {
                return new ArrayList<>();
            }
            List<String> lst = (List<String>) map2.get("suggestion");
            for (int i = 0; i < lst.size(); i++) {
                rtn.add(lst.get(i));
            }
        }

        return rtn;
    }

    @Override
    public SearResp regular(String queryStr, Integer start, Integer size) {
        return searchQuery(queryStr, start, size);
    }

    @Override
    public void delete(String id) {
        try {
            solr.deleteById(id);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteByIds(List<String> idList) {
        try {
            solr.deleteById(idList);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteByPhones(List<String> phoneList) {
        StringBuffer sb = new StringBuffer();
        for (String phone : phoneList) {
            if (sb.length() > 0) {
                sb.append(" OR ");
            }
            sb.append(phone);
        }
        sb.insert(0, "phone:(").append(")");
        try {
            solr.deleteByQuery(sb.toString());
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteByAddTime(String begin, String end) {
        try {
            solr.deleteByQuery("addTime:[" + begin + " TO " + end + "]");
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateStatusByIds(List<String> idList, Integer status) {
        List<SolrInputDocument> list = new ArrayList<>();
        for (String id : idList) {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", id);
            Map<String, Integer> map = new HashMap<>();
            map.put("set", status);
            document.addField("status", map);
            list.add(document);
        }
        try {
            solr.add(list);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insert(PhoneEntity phoneEntity) {
        SolrInputDocument document = buildSolrDoc(phoneEntity);
        try {
            solr.add(document);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PhoneEntity searchById(String id) {
        return queryOne("id", id);
    }

    @Override
    public PhoneEntity searchByPhone(String phone) {
        return queryOne("phone", phone);
    }

    @Override
    public SearResp search(SearPage searPage) {
        SolrQuery query = getQuery(searPage);
        try {
            QueryResponse response = solr.query(query);
            SearResp searResp = new SearResp(searPage.getStart(), searPage.getSize(), response.getResults().getNumFound());
            searResp.setData(getEntity(response));
            return searResp;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public SearResp searchNull(String field, Integer start, Integer size) {
        return searchQuery("-(" + field + ":*)", start, size);
    }

    public void deleteBySupplier(String supplier) {
        try {
            solr.deleteByQuery("supplier:" + supplier);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

97年的典藏版

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值