springcloud-es的学习

springcloud-es的学习,第1张

springcloud-es的学习

  

GET _search
{
  "query": {
    "match_all": {}
  }
}
#创建索引
PUT /zxy
{
  "mappings":{
      "properties":{
          "info":{
              "type":"text",
              "analyzer":"ik_smart"
          },
          "email":{
              "type":"keyword",
              "index":false
          },
          "name":{
              "type":"object",
              "properties":{
                  "firstName":{
                      "type":"keyword"
                  },
                  "lastName":{
                      "type":"keyword"
                  }
              }
          }
      }
  }
}
#新添索引字段
PUT /zxy/_mapping
{
  "properties":{
    "age":{
      "type":"integer"
    }
  }
}

GET /zxy
#插入文档
POST /zxy/_doc/1
{
  "age":"21",
  "email":"[email protected]",
  "info":"哈哈有几个哈",
  "name":{
    "firstName":"赵",
    "lastName":"兴宇"
  }
}
#查询文档
GET /zxy/_doc/1

#删除文档
DELETe /zxy/_doc/1

# 一.全量修改 全部修改   id存在就是修改,不存在就是新增
PUT /zxy/_doc/1
{
  "age":"21",
  "email":"[email protected]",
  "info":"哈哈有几个哈",
  "name":{
    "firstName":"赵",
    "lastName":"兴宇"
  }
}

#局部修改文档字段
POST /zxy/_update/1
{
  "doc":{
    "info":"纱雾天下第一!"
  }
}


#酒店的mapping
PUT /hotel
{
  "mappings": {
    "properties": {
      "id":{
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "ik_max_word",
        "copy_to": "all"
      },
      "address":{
        "type": "keyword",
        "index": false
      },
      "price":{
        "type": "integer"
      },
      "score":{
        "type": "integer"
      },
      "brand":{
        "type": "keyword",
        "copy_to": "all"
      },
      "city":{
        "type": "keyword"
      },
      "starName":{
        "type": "keyword"
      },
      "business":{
        "type": "keyword",
        "copy_to": "all"
      },
      "location":{
        "type": "geo_point"
      },
      "pic":{
        "type": "keyword",
        "index": false
      },
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

GET /hotel

DELETE /hotel


GET /hotel/_doc/47478

#批量查询
GET /hotel/_search

#查询所有
GET /hotel/_search
{
  "query": {
    "match_all": {
      
    }
  }
}

#全文检索查询
GET /hotel/_search
{
  "query": {
    "match": {
      "all": "北京"
    }
  }
}

#允许同时查询多个字段
GET /hotel/_search
{
  "query": {
    "multi_match": {
      "query": "五星级",
      "fields": ["city","brand","starName"]
    }
  }
}
 
#精确查询,查找keyword 不可分词 
# term对值查询(完全一致才行)
GET /hotel/_search
{
  "query": {
    "term": {
      "city": {
        "value": "北京"
      }
    }
  }
}

#精确查询 ,对范围查询   
# gte:#大于等于  lte :#小于等于  没有e就是没有等于
GET /hotel/_search
{
  "query": {
    "range": {
      "price": {
        
        "gte": 200, 
        "lte": 300    
      }
    }
  }
}

#地理查询
# geo_bounding_box: 查询geo_point值落在某个矩形范围的所有文档
GET /hotel/_search
{
  "query": {
    "geo_bounding_box":{
      "location":{
        "top_left":{
          "lat":31.1,
          "lon":121.5
        },
        "bottom_right":{
          "lat":30.9,
          "lon":121.7
        }
      }
    }
  }
}

#geo_distance:查询到指定中心点小于某个距离值的所有文档

GET /hotel/_search
{
  "query": {
    "geo_distance":{
      "distance":"5km",
      "location":"31.21, 121.5"
    }
  }
}


#复合查询 将其他简单查询组合起来 实现更复杂的搜索逻辑
#function score :算分函数查询,算分控制文档排名



#高亮
GET /hotel/_search
{
  "query": {
    "match": {
      "all": "如家"
    }
  },
  "highlight": {
    "fields": {
      "name":{
        "require_field_match": "false"
      }
    }
  }
}






public class HotelIndexTest {

    private RestHighLevelClient client;


    @Test
    void testInit() {
        System.out.println(client);
    }

    
    @Test
    void createHotelIndex() throws IOException {
        // 1.创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.准备请求的参数: DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        // 3.发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    
    @Test
    void existsHotelIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hotel");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.err.println(exists ? "索引库已经存在" : "索引库不存在");
    }

    
    @Test
    void getHotelIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hotel");
        GetIndexResponse hotel = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println(hotel.getMappings());

    }

    
    @Test
    void deleteHotelIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }


    //连接  ,最前
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
                //可多个 集群配置
//                HttpHost.create("http://localhost:9200")
        ));
    }

    //结束释放资源,最后
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}


@SpringBootTest
public class HoteldocumentTest {


    private RestHighLevelClient client;

    @Autowired
    private IHotelService hotelService;

    @Test
    void testInit() {
        System.out.println(client);
    }

    
    @Test
    void testIndexdocument() throws IOException {
        //根据id查询酒店数据
        Hotel hotel = hotelService.getById(38609L);
        // 因为文档的location只有一个字段,把经纬度合在一起,所以将其转换
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());

        // 2.准备JSON文档
        request.source(JSON.toJSonString(hotelDoc), XContentType.JSON);

        // 3. 发送请求
        client.index(request, RequestOptions.DEFAULT);
    }


    
    @Test
    void testGetdocumentById() throws IOException {

        GetRequest request = new GetRequest("hotel", "38609");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);

        String json = response.getSourceAsString();
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
        System.out.println(json);
    }


    
    @Test
    void testDeletedocumentById() throws IOException {

        DeleteRequest request = new DeleteRequest("hotel", "38609");
        client.delete(request, RequestOptions.DEFAULT);
    }


    
    @Test
    void testExistsdocumentById() throws IOException {

        GetRequest request = new GetRequest("hotel", "38609");
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists ? "文档存在" : "文档不存在");

    }

    
    @Test
    void testUpdatedocumentById() throws IOException {

        UpdateRequest request = new UpdateRequest("hotel", "38609");
        // 2.准备参数,每两个参数为一对 key value;
        request.doc(
                "city","贵州",
                "name","赵兴宇家酒店"
        );
        client.update(request,RequestOptions.DEFAULT);

    }


    
    @Test
    void testBulkRequest() throws IOException {

        List hotels = hotelService.list();


        // 1.创建request
        BulkRequest request = new BulkRequest();
        // 2.准备参数,添加多个新增的request
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(
                    new IndexRequest("hotel")
                            .id(hotel.getId().toString())
                            .source(JSON.toJSonString(hotelDoc),XContentType.JSON)
            );
            // 可以批量新增,删除,修改
//            request.add(new UpdateRequest());
        }
        // 3.发送请求
        client.bulk(request,RequestOptions.DEFAULT);
    }


    
    @Test
    void testSearchdocument() throws IOException {

        SearchRequest request = new SearchRequest("hotel");


        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        System.out.println(response);

    }



    //连接  ,最前
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
                //可多个 集群配置
//                HttpHost.create("http://localhost:9200")
        ));
    }

    //结束释放资源,最后
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

}





public class RestClientdocumentTest {

    private RestHighLevelClient client;

    
    @Test
    void testMatchAll() throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL参数
        request.source()
                .query(QueryBuilders.matchAllQuery());
        // 3.发送请求,得到相应结果
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应结果
        SearchHits searchHits = response.getHits();
        //4.1查询的总条数
        handleResponse(searchHits);

    }

    
    @Test
    void testMatch() throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL参数
        //(1).全文检索查询
        request.source()
                .query(QueryBuilders.matchQuery("all", "如家"));
        //(2).多字段查询
        request.source()
                .query(QueryBuilders.multiMatchQuery("如家", "name", "business"));
        //(3).termQuery精确查询(词条查询)
        request.source()
                .query(QueryBuilders.termQuery("city", "上海"));
        //(4).范围查询
        request.source()
                .query(QueryBuilders.rangeQuery("price").gte(100).lte(150));
        //(5).复合查询

        //(5).1创建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //(5).2添加term查询
        boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
        //(5).3谭家range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
        //将条件添加进请求
        request.source().query(boolQuery);

        // 3.发送请求,得到相应结果
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应结果
        SearchHits searchHits = response.getHits();
        //4.1查询的总条数
        handleResponse(searchHits);

    }

    
    @Test
    void testSource() throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL参数
        request.source()
                .query(QueryBuilders.matchAllQuery());

        //分页
        request.source().from(0).size(5);
        //价格高亮显示
        request.source().highlighter(new HighlightBuilder()
                .field("name")
                //是否需要与匹配字段对应
                .requireFieldMatch(false)
        );
        //价格排序
        request.source().sort("price", SortOrder.ASC);
        // 3.发送请求,得到相应结果
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应结果
        SearchHits searchHits = response.getHits();
        //抽离函数
        handleResponse(searchHits);

    }


    
    private void handleResponse(SearchHits searchHits) {
        long total = searchHits.getTotalHits().value;
        System.out.println("一共有:" + total + "条数据");
        //4.2查询的结果数组
        SearchHit[] hits = searchHits.getHits();

        for (SearchHit hit : hits) {
            //4.3得到source
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取高亮字段
            Map highlightFields = hit.getHighlightFields();

            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField highlightField = highlightFields.get("name");

                if (highlightField != null) {
                    String name = highlightField.getFragments()[0].string();
                    hotelDoc.setName(name);
                }

            }
            //4.4打印
            System.out.println(hotelDoc);
        }
    }

    @Test
    void name() {


    }

//    @Test
//    void name() {
//    }
//
//    @Test
//    void name() {
//    }

    //连接  ,最前
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
                //可多个 集群配置
//                HttpHost.create("http://localhost:9200")
        ));
    }

    //结束释放资源,最后
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}



















欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5708680.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存