码迷,mamicode.com
首页 > 编程语言 > 详细

java整合Elasticsearch,实现crud以及高级的分页,范围,排序功能

时间:2019-07-24 13:10:12      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:pos   RKE   修改   cep   inf   date   BMI   分词   async   

//为index创建mapping,index相当于mysql的数据库,数据库里的表也要给各个字段创建类型,所以index也要给字段事先设置好类型:

使用postMan或者其他工具创建:(此处我使用postMan,创建一个名为shop的index,type是order-- type相等于mysql的表)

//这里的背景是一个订单表对应多个订单项表(商品信息),然后就将所有的订单和购买的商品信息存到ES,我这里的ES版本是6.4.2

put localthost:9200/shop

{
"mappings": {
"order": {
"dynamic": false,//设置为false的意思就是以后不能动态添加字段
"properties": {
"orderId": {
"type": "keyword", // 字符串类型只有textkeyword,text是会分词
"index": true //如果要以该字段作为搜索条件,就必须写成true
},
"orderAmount": {
"type": "double"
},
"orderTitle": {
"type": "text",
"analyzer": "english"
},
"customerId": {
"type": "keyword",
"index": true
},
"orderSubmit": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"payTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"finshiTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"expressAmount": {
"type": "double"
},
"deliveryTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"couponAmount": {
"type": "double"
},
"score": {
"type": "integer"
},
"scoreAmount": {
"type": "double"
},
"orderStatus": {
"type": "integer"
},
"paymentStatus": {
"type": "integer"
},
"markertId": {
"type": "keyword",
"index": true
},
"shopId": {
"type": "keyword",
"index": true
},
"shopName": {
"type": "text",
"analyzer": "english"
},
"address": {
"type": "text",
"analyzer": "standard"
},
"recieveName": {
"type": "text",
"analyzer": "standard"
},
"phone": {
"type": "keyword",
"index": true
},
"itemList": {
"properties": {
"orderItemId": {
"type": "keyword",
"index": true
},
"itemId": {
"type": "keyword",
"index": true
},
"itemTitle": {
"type": "text",
"analyzer": "english"
},
"itemType": {
"type": "integer"
},
"quanity": {
"type": "integer"
},
"price": {
"type": "double"
},
"totalAmount": {
"type": "double"
}
}
}
}
}
}
}
//创建完成后,使用es可视化工具(我使用的是head)在浏览器登录可以看到对应的shop索引了

技术图片

//ES的order对象结构如下:

public class EsOrderMast {
    private String orderId;
    private BigDecimal orderAmount;
    private String orderTitle;
    private String customerId;
    private String  orderSubmit;
    private String  payTime;
    private String finshiTime;
    private BigDecimal expressAmount;
    private String deliveryTime;
    private BigDecimal couponAmount;
    private Integer score;
    private BigDecimal scoreAmount;
    private Integer orderStatus;
    private Integer paymentStatus;
    private String markertId;
    private String shopId;
    private String shopName;
    private String address;
    private String recieveName;
    private String phone;
    private List<EsOrderItem> itemList=new ArrayList<>();//订单的商品信息
}//省略了setter和getter

 //订单的商品ES对象结构:

public class EsOrderItem {

    private String orderItemId;

    private String itemId;

    private String itemTitle;

    private Integer itemType;

    private Integer quanity;

    private BigDecimal price;

    private BigDecimal totalAmount;
}//省略setter和getter

//第一步创建java客户端

public abstract class ESUtil {

    private static TransportClient client = null;



    public static TransportClient getClient()  {
        if(client==null){
            Settings settings = Settings.builder().put("cluster.name", "yangxiaohui").build();//集群名称在es的配置文件可以找到
            try {
                client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return client;
    }

}

//将数据库的信息查询出来,然后批量初始化到ES中

//批量新增
    @Async //异步方式
    public void initESOrderMast() {
        List<EsOrderMast> esItemList = orderMastMapper.findEsItemList();
        TransportClient client = ESUtil.getClient();
        BulkRequest bulkRequest = new BulkRequest();
        if(null!=esItemList && esItemList.size()>0){
            for (EsOrderMast esOrderMast : esItemList) {
                IndexRequest indexRequest = new IndexRequest("shop", "order", esOrderMast.getOrderId());
                indexRequest.source(JSON.toJSONString(esOrderMast), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
        }
        ActionFuture<BulkResponse> bulk = client.bulk(bulkRequest);
        System.out.println(bulk.isDone());
        BulkResponse bulkItemResponses = bulk.actionGet();
        System.out.println(bulkItemResponses.status().getStatus());

    }

//下面是增删改查代码

 //删除
    public boolean deleteByOrderId(String orderId){
        boolean flag =false;
        TransportClient client = ESUtil.getClient();
        ActionFuture<DeleteResponse> actionFuture = client.delete(new DeleteRequest("shop", "order", orderId));
        flag = actionFuture.isDone();
        DeleteResponse deleteResponse = actionFuture.actionGet();
        System.out.println(deleteResponse.getResult().toString());
        System.out.println(deleteResponse.status().getStatus());
        return flag;
    }
    //查找
    public EsOrderMast getOrderByOrderId(String orderId){
        EsOrderMast esOrderMast=null;
        TransportClient client = ESUtil.getClient();
        GetRequestBuilder getRequestBuilder = client.prepareGet("shop", "order", orderId);
        GetResponse response = getRequestBuilder.get();
        String sourceAsString = response.getSourceAsString();
        esOrderMast = JSON.parseObject(sourceAsString, EsOrderMast.class);
        return esOrderMast;
    }
    //修改
    public boolean update(String orderId,Integer orderStatus) {
        EsOrderMast orderMast = getOrderByOrderId(orderId);
        orderMast.setOrderStatus(orderStatus);
        orderMast.setFinshiTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        TransportClient client = ESUtil.getClient();
        //UpdateResponse updateResponse = client.prepareUpdate("shopdb", "order", orderId).setDoc(JSON.toJSONString(orderMast), XContentType.JSON).execute().actionGet();
       /* UpdateRequest request = new UpdateRequest("", "order", orderId);
        request.doc(JSON.toJSON(orderMast),XContentType.JSON);*/


        //client.update(request).get();
        UpdateResponse updateResponse = client.prepareUpdate("shop", "order", orderId)
                .setDoc(JSON.toJSON(orderMast),XContentType.JSON).get();
        //System.out.println(update.actionGet().status().getStatus());

        return updateResponse.status().getStatus()==200?true:false;


    }

//高级查询:分页,排序,范围查找:

先看高级查询请求对象:

public class EsQueryObject {
    private String orderId;

    private String customerId;

    private String txtOrderTitle;

    private Integer orderStatus;

    private Integer paymentStatus;

    private String phone;

    private String recieveName;

    private String addresss;

    private String orderSubmitTime_S;
    private String orderSubmitTime_E;

    private String payTime_S;
    private String payTime_E;

    private BigDecimal minPayAmount;

    private BigDecimal maxPayAmount;

    private String shopId;

    private String itemId;

    private String itemTile;

    private Page page;
}

//高级查询方法:

public List<EsOrderMast> findOrderList(EsQueryObject queryObject){
        TransportClient client = ESUtil.getClient();
        SearchRequestBuilder sourceBuilder=client.prepareSearch("shop");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(!StringUtils.isEmpty(queryObject.getOrderId())){
            boolQueryBuilder.must(QueryBuilders.termQuery("orderId",queryObject.getOrderId()));
        }
        if(!StringUtils.isEmpty(queryObject.getCustomerId())){
            boolQueryBuilder.must(QueryBuilders.termQuery("customerId",queryObject.getCustomerId()));
        }
        if(!StringUtils.isEmpty(queryObject.getTxtOrderTitle())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("orderTitle",queryObject.getTxtOrderTitle()));
        }

        if(null!=queryObject.getOrderStatus() && queryObject.getOrderStatus()>=0){
            boolQueryBuilder.must(QueryBuilders.termQuery("orderStatus",queryObject.getOrderStatus()));
        }
        if(null!=queryObject.getPaymentStatus() && queryObject.getPaymentStatus()>=0){
            boolQueryBuilder.must(QueryBuilders.termQuery("paymentStatus",queryObject.getPaymentStatus()));
        }
        if(!StringUtils.isEmpty(queryObject.getPhone())){
            boolQueryBuilder.must(QueryBuilders.termQuery("phone",queryObject.getPhone()));
        }
        if(!StringUtils.isEmpty(queryObject.getRecieveName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("recieveName",queryObject.getRecieveName()));
        }
        if(!StringUtils.isEmpty(queryObject.getAddresss())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("addresss",queryObject.getAddresss()));
        }

        if(!StringUtils.isEmpty(queryObject.getShopId())){
            boolQueryBuilder.must(QueryBuilders.termQuery("shopId",queryObject.getShopId()));
        }
        if(!StringUtils.isEmpty(queryObject.getItemId())){
            boolQueryBuilder.must(QueryBuilders.termQuery("itemList.itemId",queryObject.getItemId()));
        }
        if(!StringUtils.isEmpty(queryObject.getItemTile())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("itemList.itemTitle",queryObject.getItemTile()));
        }


        if(!StringUtils.isEmpty(queryObject.getOrderSubmitTime_S())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("orderSubmit").gte(queryObject.getOrderSubmitTime_S()));
        }
        if(!StringUtils.isEmpty(queryObject.getOrderSubmitTime_E())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("orderSubmit").lte(queryObject.getOrderSubmitTime_E()));
        }
        if(!StringUtils.isEmpty(queryObject.getPayTime_S())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("payTime").gte(queryObject.getPayTime_S()));
        }
        if(!StringUtils.isEmpty(queryObject.getPayTime_E())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("payTime").lte(queryObject.getPayTime_E()));
        }

        if(null!=queryObject.getMinPayAmount()){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("orderAmount").gte(queryObject.getMinPayAmount().doubleValue()));
        }
        if(null!=queryObject.getMaxPayAmount()){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("orderAmount").lte(queryObject.getMaxPayAmount().doubleValue()));
        }
        sourceBuilder.setQuery(boolQueryBuilder);
        sourceBuilder.addSort(SortBuilders.fieldSort("orderSubmit").order(SortOrder.ASC));//排序
        if(null!=queryObject.getPage()){
            Page page = queryObject.getPage();
            int num = page.getNum();
            int pageSize = page.getPageSize()==0?10:page.getPageSize();
            sourceBuilder.setFrom(num).setSize(pageSize);

        }
        List<EsOrderMast> list = new ArrayList<>();
        ActionFuture<SearchResponse> execute = sourceBuilder.execute();
        SearchResponse searchResponse = null;
        try {
            searchResponse = execute.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        SearchHits hits = searchResponse.getHits();
        if(null!=hits && hits.totalHits>0) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                EsOrderMast orderMast = JSON.parseObject(sourceAsString, EsOrderMast.class);
                list.add(orderMast);
            }
        }
        return list;


    }

//附上maven

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.4.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>




java整合Elasticsearch,实现crud以及高级的分页,范围,排序功能

标签:pos   RKE   修改   cep   inf   date   BMI   分词   async   

原文地址:https://www.cnblogs.com/yangxiaohui227/p/11237268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!