Elasticserach——RestAPI操作ES

https://www.elastic.co/guide/en/elasticsearch/client/index.html
2.1、环境准备
第一步:创建一个maven工程

第二步:导入依赖

 
    org.springframework.boot
    spring-boot-starter-parent
    2.1.3.RELEASE


    
        org.elasticsearch.client
        elasticsearch-rest-high-level-client
        6.4.3
    

    org.springframework.boot
    spring-boot-starter-test



    org.projectlombok
    lombok



    org.springframework.boot
    spring-boot-starter-logging


    com.google.code.gson
    gson



    org.apache.commons
    commons-lang3
    3.8.1


    com.alibaba
    fastjson
    1.2.47


第三步:准备客户端

public class ESManager {
    RestHighLevelClient client = null;
    @Before
    public void init() throws Exception{
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9201, "http"),
                        new HttpHost("127.0.0.1", 9202, "http"),
                        new HttpHost("127.0.0.1", 9203, "http")));
    }




    @After
    public void end() throws Exception{
        client.close();
    }
}

第四步:使用kibana创建索引库index、类型type、映射mapping

PUT /item
{
  "mappings": {
    "docs": {
      "properties": {
        "id": {
          "type": "keyword"
       },
        "title": {
          "type": "text",
          "analyzer": "ik_max_word"
       },
        "category": {
          "type": "keyword"
       },
        "brand": {
          "type": "keyword"
       },
        "images": {
          "type": "keyword",
          "index":  false
       },
        "price": {
          "type": "double"
       }
     }
   }
 }
}

第五步:准备一个实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Item {
    private String id;     //不分词
    private String title; //标题   分词
    private String category;// 分类   不分词
    private String brand; // 品牌     不分词
    private Double price; // 价格    不分词
    private String images; // 图片地址   不分词
}

2.2、文档的操作
向es中放入数据
新增和修改

@Test
public void testDoc() throws Exception{
    Item item = new Item("1","小米9手机","手机","小米",1199.0,"q3311");
//        IndexRequest专门用来插入索引数据的对象
        IndexRequest request = new IndexRequest( "item","docs",item.getId());
//        把对象转成json字符串
//        String jsonString = JSON.toJSONString(item);  //fastjson转json的方式
        String jsonString = gson.toJson(item);   //gson转json的方式
        request.source(jsonString, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

删除

		@Test
		public void testdeleteDoc() throws Exception{
		    DeleteRequest request = new DeleteRequest("item","docs","1");
		    client.delete(request, RequestOptions.DEFAULT);
		}

批量新增

@Test
public void testBulkAddDoc() throws Exception{
List list = new ArrayList<>();
list.add(new Item("1", "小米手机7", "手机", "小米", 3299.00,"http://image.leyou.com/13123.jpg"));
list.add(new Item("2", "坚果手机R1", "手机", "锤子", 3699.00,"http://image.leyou.com/13123.jpg"));   
 list.add(new Item("3", "华为META10", "手机", "华为",4499.00,"http://image.leyou.com/13123.jpg"));
list.add(new Item("4", "小米Mix2S", "手机", "小米", 4299.00, "http://image.leyou.com/13123.jpg")); 
list.add(new Item("5", "荣耀V10", "手机", "华为",  2799.00,"http://image.leyou.com/13123.jpg"));
BulkRequest request = new BulkRequest();
   /* for (Item item : list) {
        IndexRequest indexRequest = new IndexRequest( "item","docs",item.getId());
        String jsonString = gson.toJson(item);   //gson转json的方式
        indexRequest.source(jsonString, XContentType.JSON);
        request.add(indexRequest);
    }*/
    list.forEach(item->{  //流式编程
        IndexRequest indexRequest = new IndexRequest( "item","docs",item.getId());
        String jsonString = gson.toJson(item);   //gson转json的方式
        indexRequest.source(jsonString, XContentType.JSON);
        request.add(indexRequest);
    });
    client.bulk(request,RequestOptions.DEFAULT);
}

2.3、各种查询

  @Test
   public void testSearch() throws Exception{
  //        构建一个用来查询的对象
    SearchRequest searchRequest = new SearchRequest("item").types("docs");
       //构建查询方式
 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
     //   查询所有
 // searchSourceBuilder.query(QueryBuilders.matchAllQuery());
 // term查询      
 searchSourceBuilder.query(QueryBuilders.termQuery("title","小米"));
  //  searchSourceBuilder.query(QueryBuilders.matchQuery());
   //   searchSourceBuilder.query(QueryBuilders.wildcardQuery());             
  // searchSourceBuilder.query(QueryBuilders.fuzzyQuery());
//     放入到searchRequest中
    searchRequest.source(searchSourceBuilder); 
//        执行查询
      SearchResponse searchResponse =   client.search(searchRequest,RequestOptions.DEFAULT);
      SearchHits responseHits =      searchResponse.getHits();
      
      System.out.println("总记录数      是:"+responseHits.getTotalHits());

    SearchHit[] searchHits = responseHits.getHits();

    for (SearchHit searchHit : searchHits) {
 //            把json字符串转成对象
        String jsonString = searchHit.getSourceAsString();
            fastjson
//            Item item = JSON.parseObject(jsonString, Item.class);
//            gson
        Item item = gson.fromJson(jsonString, Item.class);
        System.out.println(item);
    }
}

2.4、过滤
显示字段的过滤
在这里插入图片描述
数据的过滤

searchSourceBuilder.query(QueryBuilders.termQuery("title","手机"));
searchSourceBuilder.postFilter(QueryBuilders.termQuery("brand","锤子"));

2.5、分页

searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.from(0);
searchSourceBuilder.size(2);

2.6、排序

searchSourceBuilder.sort("price", SortOrder.DESC);

2.7、高亮
Elasticserach——RestAPI操作ES_第1张图片
构建高亮的条件

   HighlightBuilder highlightBuilder = new HighlightBuilder();
       highlightBuilder.field("title");
       highlightBuilder.preTags("");
       highlightBuilder.postTags("");
//        "fields": {"title": {}},
//        "pre_tags": "",
//                "post_tags": ""
       searchSourceBuilder.highlighter(highlightBuilder);

获取高亮的结果

String jsonString = searchHit.getSourceAsString();
Item item = gson.fromJson(jsonString, Item.class);
Map highlightFields = searchHit.getHighlightFields();
HighlightField highlightField = highlightFields.get("title");
Text[] fragments = highlightField.getFragments(); 
if(fragments!=null&&fragments.length>0){
    String title = fragments[0].toString();
    item.setTitle(title); //把item的title替换成高亮的数据
}

2.8、聚合
需求:统计每个品牌的数量
Elasticserach——RestAPI操作ES_第2张图片

构建聚合的条件

 searchSourceBuilder.aggregation(AggregationBuilders.terms("brandCount").field("brand"));

获取聚合结果

    Aggregations aggregations = searchResponse.getAggregations();
    Terms terms = aggregations.get("brandCount");
    List buckets = terms.getBuckets();
    buckets.forEach(bucket->{
	//            bucket:{
	//                "key": "华为",
	//                        "doc_count": 2
	//            }
	            System.out.println( bucket.getKeyAsString()+":"+bucket.getDocCount());
	        });

你可能感兴趣的:(Elasticsearch,Elasticsearch)