Elasticserach——RestAPI操作ES

  • Post author:
  • Post category:其他


https://www.elastic.co/guide/en/elasticsearch/client/index.html

2.1、环境准备

第一步:创建一个maven工程

第二步:导入依赖

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.4.3</version>
    </dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>
</dependencies>

第三步:准备客户端

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<Item> 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、高亮

在这里插入图片描述

构建高亮的条件

   HighlightBuilder highlightBuilder = new HighlightBuilder();
       highlightBuilder.field("title");
       highlightBuilder.preTags("<span style='color:red'>");
       highlightBuilder.postTags("</span>");
//        "fields": {"title": {}},
//        "pre_tags": "<span style='color:red'>",
//                "post_tags": "</span>"
       searchSourceBuilder.highlighter(highlightBuilder);

获取高亮的结果

String jsonString = searchHit.getSourceAsString();
Item item = gson.fromJson(jsonString, Item.class);
Map<String, HighlightField> 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、聚合

需求:统计每个品牌的数量

在这里插入图片描述

构建聚合的条件

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

获取聚合结果

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



版权声明:本文为qq_41080067原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。