1. 程式人生 > >Solr REST操作:增刪改查

Solr REST操作:增刪改查

     在使用solr時,對solr進行操作可以solr4j直接操作,但在對solr multicore進行操作時(如資料庫分表)有些不方便,因此嘗試了直接採用REST形式進行操作

public class SolrServiceImpl implements SolrService {

    @Override
public boolean addIndex(List<Program> list) { 
        JSONArray array = new JSONArray();
        for (Program p : list) {
            JSONObject object = new 
JSONObject(); object.put("id", p.getId()); object.put("name", p.getName()); array.add(object); } String result = HttpUtils.httpPost("http://localhost:8080/solr/update?commit=true", array.toString()); JSONObject resultObj = JSON.parseObject(result); int status = resultObj.getJSONObject("responseHeader"
).getIntValue("status"); return status == 0; } @Override public boolean addIndex(Program program) { List<Program> list = new ArrayList<>(); list.add(program); return addIndex(list); } @Override public boolean updateIndexById(Program program) { List<Program> list = new
ArrayList<>(); list.add(program); return addIndex(list); } @Override public boolean deleteIndex(long id) { //{"delete":[ {"id":"3"}} JSONObject idObj = new JSONObject(); idObj.put("id", id); JSONObject delObj = new JSONObject(); delObj.put("delete", idObj); String result = HttpUtils.httpPost("http://localhost:8080/solr/update?commit=true", delObj.toString()); JSONObject resultObj = JSON.parseObject(result); int status = resultObj.getJSONObject("responseHeader").getIntValue("status"); return status == 0; } @Override public SolrResult select(List<Integer> websiteIds, String keyword, int start, int num) { SolrResult solrResult = new SolrResult(); String result = HttpUtils.httpGet("http://localhost:8080/solr/select?q=*:*&wt=json&start"+start+"&rows="+num); if (StringUtils.isNotEmpty(result)) { JSONObject jsonObject = JSON.parseObject(result); JSONObject respObj = jsonObject.getJSONObject("response"); if (respObj != null) { int totals = respObj.getIntValue("numFound"); solrResult.setTotalCount(totals); JSONArray docsArr = respObj.getJSONArray("docs"); int size = docsArr.size(); List<Program> programList = new ArrayList<>(); for (int index = 0; index < size; index++) { JSONObject docObj = docsArr.getJSONObject(index); Program program = new Program(); program.setPname(docObj.getString("name")); program.setId(docObj.getLongValue("id")); programList.add(program); } solrResult.setProgramList(programList); } } return solrResult; } }

如果需要進行關聯多核進行查詢時,可以採用如下形式:

http://localhost:8080/solr/core_1/select?shards=http://localhost:8080/solr/core_0,http://localhost:8080/solr/core_1&wt=json&q=%E4%BA%86&start=0&rows=10