Use java reflection mechanism to write solr general java client

I. Introduction

  Through the explanation in the previous article, we know the dynamicFiled field, which is dynamic and does not require a displayed declaration. And some commonly used basic types solr have been created for us by default.

  For example: *_i, *_is, etc.

  If we want to use dynamic fields, the naming of the fields needs to conform to the above rules. Solr provides us with a large number of dynamic fields:

  

Second, the preparation of entity classes

  Here, we take the creation of the index of the product as an example, and the creation of the entity is as follows:

copy code
@Getter@Setter
public class Product {
  //Commodity id, and it is a required field
    private String id;
   //Commodity name, it is a string type, so we end with "_s"
    private String proName_s;
  //The commodity structure is double type, so it ends with "_d"
    private Double price_d;
  //The product classification is a string type, and a product can have multiple classifications, which are multi-valued, so we end with "_ss"
    private List<String> tag_ss;
}
copy code

3. Solrj writes java general client

  We mainly write through java's reflection mechanism and generics:

copy code
package com.urwork.tools.solr;

import com.urwork.tools.page.Page;
import org.apache.commons.collections.CollectionUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xxx on xxxx/xx/xx.
 */
public class SolrCloudClient {
    private CloudSolrClient server=null;

    /**
     * Constructor
     * @param zkAddr zk address: 192.168.2.233:2181,192.168.2.234:2181,192.168.2.235:2181
     * @param collection    collection名字: company
     */
    private SolrCloudClient(String zkAddr,String collection) {
        server = new CloudSolrClient.Builder().withZkHost(zkAddr).build();
        server.setDefaultCollection(collection);
    }

    /**
     * delete all data in the collection
     * @throws Exception
     */
    public void deleteAll() throws Exception {
        server.deleteByQuery("*:*");
        server.commit();
    }

    /**
     * Delete the data in the collection according to the id
     * @param id
     * @throws Exception
     */
    public void deleteById(String id) throws Exception {
        server.deleteById(id);
        server.commit();
    }

    /**
     * Delete the data in the collection based on ids
     * @param ids
     * @throws Exception
     */
    public void deleteByIds(List<String> ids) throws Exception {
        server.deleteById(ids);
        server.commit();
    }

    /**
     * Batch update index
     * @param docs
     * @param <T>
     * @throws Exception
     */
    public <T> void addList(List<T> docs) throws Exception {
        if (CollectionUtils.isEmpty(docs)){
            return;
        }
        List<SolrInputDocument> list = new ArrayList<>();
        for (T doc:docs){
            Field[] declaredFields = doc.getClass().getDeclaredFields();
            SolrInputDocument sid = new SolrInputDocument();
            for (Field field : declaredFields){
                field.setAccessible(true);
                String name = field.getName();
                Object value = field.get(doc);
                if (value!=null){
                    sid.addField(name,value);
                }
                list.add(sid);
            }
        }

        server.add(list);
        server.commit();
    }

    /**
     * Add a single index
     * @param doc
     * @param <T>
     * @throws Exception
     */
    public <T> void add(T doc) throws Exception {
        List<T> docs = new ArrayList<>();
        docs.add(doc);
        addList(docs);
    }

    /**
     * update an index
     * @param doc
     * @param <T>
     * @throws Exception
     */
    public <T> void update(T doc)throws Exception{
        Field idField = doc.getClass().getDeclaredField("id");
        if (idField == null){
            throw new RuntimeException("your document doesn't have id");
        }
        idField.setAccessible(true);
        Object id = idField.get(doc);
        deleteById(id+"");
        add(doc);
    }

    /**
     * Batch update index
     * @param docs
     * @param <T>
     * @throws Exception
     */
    public <T> void updateList(List<T> docs) throws Exception {
        if (CollectionUtils.isEmpty(docs)){
            return;
        }
        List<String> ids = new ArrayList<>();
        for (T doc : docs){
            Field idField = doc.getClass().getDeclaredField("id");
            if (idField!=null){
                idField.setAccessible(true);
                Object id = idField.get(doc);
                ids.add(id+"");
            }
        }
        deleteByIds(ids);
        addList(docs);
    }

    /**
     * execute query
     * @param clazz corresponding class
     * @param page Page paging
     * @param query query condition
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> Page<T> search(Class<T> clazz,Page<T> page, SolrQuery query) throws Exception {
        query.setStart((page.getCurrentPageNo()-1)*page.getPageSize());
        query.setRows(page.getPageSize());

        QueryResponse response = server.query(query);
        SolrDocumentList results = response.getResults();
        List<T> rtnList = new ArrayList<>();
        for (SolrDocument doc : results){
            T instance = clazz.newInstance();
            Field[] declaredFields = instance.getClass().getDeclaredFields();
            for (Field filed : declaredFields){
                filed.setAccessible(true);
                String name = filed.getName();
                Object fieldValue =doc.getFieldValue(name);
                filed.set(instance,fieldValue);
            }
            rtnList.add(instance);
        }
        page.setResult(rtnList);
        page.setTotalRecord((int)results.getNumFound());
        return page;
    }

    public void close() throws IOException {
        server.close();
    }

}
copy code

  When we create an entity class, the names of the fields are named according to the rules of dynamic values. When building indexes and queries, we can use public classes to implement them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325199756&siteId=291194637