ElasticSearch

  一、什么是ElasticSearch


        ElasticSearch是一个分布式的开源搜索和分析引擎,它基于Lucene搜索引擎构建而成。它可以快速地存储、搜索和分析大规模的数据,支持多种应用场景,如网站搜索、日志分析、数据可视化等。ElasticSearch具有高效的搜索能力、分布式数据处理能力、全文检索和近实时搜索等特性,可以方便地跨多个节点分配数据,具有灵活的数据路由、复制和容错机制。同时,它还提供了RESTful API和各种客户端库,使其可以方便地与各种编程语言进行交互。

重要特性:

  • 分布式的实时文件存储,每个字段都被索引并可被搜索
  • 实时分析的分布式搜索引擎
  • 可以扩展到上百台服务器,处理PB级结构化或非结构化数据

二、倒排索引


倒排索引的概念是基于MySQL这样的正向索引而言的。

倒排索引中有两个非常重要的概念:

  • 文档( Document ):用来搜索的数据,其中的每一条数据就是一个文档。例如一个网页、一个商品信息。
  • 词条( Term ):对文档数据或用户搜索数据,利用某种算法分词,得到的具备含义的词语就是词条。例如:我是中国人,就可以分为:我、是、中国人、中国、国人这样的几个词条。

创建倒排索引是对正向索引的一种特殊处理,流程如下:

  • 将每一个文档的数据利用算法分词,得到一个个词条
  • 创建表,每行数据包括词条、词条所在文档id、位置等信息
  • 因为词条唯一性,可以给词条创建索引,例如hash表结构索引

三、正向和倒排


        正向索引是最传统的,根据id索引的方式。但根据词条查询时,必须先逐条获取每个文档,然后判断文档中是否包含所需要的词条,是根据文档找词条的过程。 而倒排索引则相反,是先找到用户要搜索的词条,根据词条得到保护词条的文档的id,然后根据 id 获取文档。是根据词条找文档的过程。

正向索引:

优点:

  • 可以给多个字段创建索引
  • 根据索引字段搜索、排序速度非常快

缺点:

  • 根据非索引字段,或者索引字段中的部分词条查找时,只能全表扫描。

倒排索引:

优点:

  • 根据词条搜索、模糊搜索时,速度非常快

缺点:

  • 只能给词条创建索引,而不是字段
  • 无法根据字段做排序

四、相关名词


文档和字段

        elasticsearch是面向文档(Document)存储的,可以是数据库中的一条商品数据,一个订单信息。文档数据会被序列化为json格式后存储在elasticsearch中,而Json文档中往往包含很多的字段(Field),类似于数据库中的

索引和映射

        索引(Index),就是相同类型的文档的集合。

        数据库的表会有约束信息,用来定义表的结构、字段的名称、类型等信息。因此,索引库中就有映射 (mapping),是索引中文档的字段约束信息,类似表的结构约束

        mapping是对索引库中文档的约束,常见的mapping属性包括:

1. type:字段数据类型,常见的简单类型有:

  • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
  • 数值:long、integer、short、byte、double、float
  • 布尔:boolean
  • 日期:date
  • 对象:object

2. index:是否创建索引,默认为true

3. analyzer:使用哪种分词器

4. properties:该字段的子字段

IK分词器

  • 创建倒排索引时对文档分词
  • 用户搜索时,对输入的内容分词
  • ik_smart:智能切分,粗粒度
  • ik_max_word:最细切分,细粒度

五、Mysql和Elasticsearch


MySQLElasticsearch说明
TableIndex索引(index),就是文档的集合,类似数据库的表(table)
RowDocument文档(Document),就是一条条的数据,类似数据库中的行(Row),文档都是JSON格式
ColumnField字段(Field),就是JSON文档中的字段,类似数据库中的列 (Column)
SchemaMappingMapping(映射)是索引中文档的约束,例如字段类型约束。类 似数据库的表结构(Schema)
SQLDSLDSL是elasticsearch提供的JSON风格的请求语句,用来操作 elasticsearch,实现CRUD

 两者各有擅长:

  • Mysql:擅长事务类型操作,可以确保数据的安全和一致性
  • Elasticsearch:擅长海量数据的搜索、分析、计算

因此两者应根据实际使用场景结合使用:

  • 对安全性要求较高的写操作,使用mysql实现
  • 对查询性能要求较高的搜索需求,使用elasticsearch实现
  • 两者再基于某种方式,实现数据的同步,保证一致性

六、索引库的CRUD


创建索引库和映射

基本语法:

  • 请求方式:PUT
  • 请求路径:/索引库名,可以自定义
http://localhost:9200/teacher
  • 请求参数:mapping映射结构
{
    //结构
    "mappings":{
        //属性
        "properties":{
            //属性1
            "age":{
                "type":"text",//文本类型
                "analyzer":"ik_smart"//分词等级:细粒度
            },
            //属性2
            "email":{
                "type":"text",
                "index":"false"//不创建索引
            },
            //属性3,object类型
            "name":{
                //子属性
                "properties":{
                    "firstName":{
                        "type":"keyword"
                    }
                }
            }
        }
    }
}

 查询索引库

基本语法:

  • 请求方式:GET
  • 请求路径:/索引库名
http://localhost:9200/teacher
  • 请求参数:无

修改索引库

        倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引,这简直是灾难。因此索引库一旦创建,无法修改mapping。

        虽然无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响。

基本语法:

  • 请求方式:PUT
  • 请求路径:/索引库名/_mapping
localhost:9200/teacher/_mapping
  • 请求参数:新增mapping
{
    "properties": {
        "新字段名":{
            "type": "integer"
        }
    }
}

删除索引库

语法:

  • 请求方式:DELETE
  • 请求路径:/索引库名
localhost:9200/teacher
  • 请求参数:无

七、文档的CRUD


新增文档

语法:

  • 请求方式:POST
  • 请求路径:/索引库名/_doc/文档id
http://localhost:9200/teacher/_doc/1
  • 请求参数:文档内容
{
    "age":"18",
    "email":"3110202314@qq.com",
    "name":{
        "firstName":"张三",
        "lastName":"李四"
    }
}

查询文档

语法:

  • 请求方式:GET
  • 请求路径:/{索引库名称}/_doc/{id}
http://localhost:9200/teacher/_doc/1
  • 请求参数:无

删除文档

语法:

  • 请求方式:DELETE
  • 请求路径:DELETE/{索引库名称}/_doc/{id}
http://localhost:9200/teacher/_doc/1
  • 请求参数:无

修改文档

  • 全量修改:直接覆盖原来的文档
  • 增量修改:修改文档中的部分字段

全量修改

全量修改是覆盖原来的文档,其本质是:

  • 根据指定的id删除文档
  • 新增一个相同id的文档

语法:

  • 请求方式:PUT
  • 请求路径:/{索引库名称}/_doc/文档id
http://localhost:9200/teacher/_doc/1
  • 请求参数:
{
    "age":"17",
    "email":"31212222124@qq.com",
    "name":{
        "firstName":"疯狂小哥",
        "lastName":"扶飞"
    }
}

增量修改

增量修改是只修改指定id匹配的文档中的部分字段。

语法:

  • 请求方式:POST
  • 请求路径:/{索引库名称}/_update/文档id
http://localhost:9200/teacher/_doc/1
  • 请求参数:
{
    "doc":{
        "eamil":"2660854394@qq.com"
    }
}

八、RestAPI


        ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES。

几个特殊字段说明:

  • location:地理坐标,里面包含精度、纬度
  • all:一个组合字段,其目的是将多字段的值利用copy_to合并,提供给用户搜索

地理坐标说明:

ES中支持两种地理坐标数据类型:

  • geo_point: 由纬度(latitude) 和经度(longitude)确定的一个点。例如:"32.8752345,120.2981576"
  • geo_shape:有多个geo_point组成的复杂几何图形。例如一条直线:"LINESTRING-77.03653 38.897676,-77.00905138.889939)"

copy_to说明:

  • 字段拷贝可以使用copy_to属性将当前字段拷贝到指定字段。示例:
"all":{
    "type":"text"
    "analyzer":"ik max word"
},
"brand":{
    "type":"keyword",
    "copy_to":"all"
}

初始化RestClient

        在elasticsearch提供的API中,与elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://localhost:9200")
));

        这里为了单元测试方便,我们创建一个测试类,然后将初始化的代码编写在 @BeforeEach方法中:

@SpringBootTest
public class HotelIndexTest{

    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

创建索引库

创建索引库的API如下:

创建一个类,定义mapping映射的JSON字符串常量:

public class HotelConstants {
    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"starName\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

在hotel-demo中的HotelIndexTest测试类中,编写单元测试,实现创建索引:

    @Test
    void createHotelIndex() throws IOException{
        CreateIndexRequest request = new CreateIndexRequest("hotels");
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
        client.indices().create(request,RequestOptions.DEFAULT);
    }

删除索引库

在hotel-demo中的HotelIndexTest测试类中,编写单元测试,实现删除索引:

    @Test
    void testDeleteHotelIndex() throws IOException {
        // 1.创建Request对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotels");
        // 2.发送请求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

判断索引库是否存在

    @Test
    void testExistsHotelIndex() throws IOException {
        // 1.创建Request对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        // 2.发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        // 3.输出
        System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
    }

总结:

        JavaRestClient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。

索引库操作的基本步骤:

  • 初始化RestHighLevelClient
  • 创建XxxIndexRequest。XXX是Create、Get、Delete
  • 准备DSL( Create时需要,其它是无参)
  • 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete

九、RestClient操作文档

新增文档

与数据库相关的实体类

@Data
@TableName("tb_hotel")
public class Hotel {
    @TableId(value = "id",type = IdType.INPUT)
    private Long id;
    @TableField(value = "name")
    private String name;
    @TableField(value = "address")
    private String address;
    @TableField(value = "price")
    private Integer price;
    @TableField(value = "score")
    private Integer score;
    @TableField(value = "brand")
    private String brand;
    @TableField(value = "city")
    private String city;
    @TableField(value = "star_name")
    private String starName;
    @TableField(value = "business")
    private String business;
    @TableField(value = "longitude")
    private String longitude;//经度
    @TableField(value = "latitude")
    private String latitude;//纬度
    @TableField(value = "pic")
    private String pic;
}

我们需要定义一个新的类型,与索引库结构吻合:

为ES索引库设计实体类,longitude和latitude需要合并为location

@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;


    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}

在hotel-demo的HotelDocumentTest测试类中,编写单元测试:

    @Test
    void testAddDocument() throws IOException {
        // 1.根据id查询酒店数据
        Hotel hotel = hotelServiceImp.getById(197837109);
        // 2.转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 3.将HotelDoc转json
        String json = JSON.toJSONString(hotelDoc);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("hotels").id(hotelDoc.getId().toString());
        // 2.准备Json文档
        request.source(json, XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

查询文档

在hotel-demo的HotelDocumentTest测试类中,编写单元测试:

    @Test
    void testGetDocumentById() throws IOException {
        // 1.准备Request
        GetRequest request = new GetRequest("hotel", "197837109");
        // 2.发送请求,得到响应
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析响应结果
        String json = response.getSourceAsString();
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

删除文档

在hotel-demo的HotelDocumentTest测试类中,编写单元测试:

    @Test
    void testDeleteDocument() throws IOException {
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("hotel", "197837109");
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

修改文档

  • 全量修改:本质是先根据id删除,再新增
  • 增量修改:修改文档中的指定字段值
  • 在RestClient的API中,全量修改与新增的API完全一致

在hotel-demo的HotelDocumentTest测试类中,编写单元测试:

    @Test
    void testUpdateDocument() throws IOException{
        UpdateRequest request = new UpdateRequest("hotels", "197837109");
        request.doc(
                "name","W酒店",
                "city","西安",
                "price","2000",
                "starName","五星级"
        );
        client.update(request, RequestOptions.DEFAULT);
    }

批量导入文档

在hotel-demo的HotelDocumentTest测试类中,编写单元测试:

    @Test
    void testBulkRequest() throws IOException{
        //批量查询酒店数据
        List<Hotel> hotels = hotelServiceImp.list();
        //创建Request
        BulkRequest request = new BulkRequest();
        //准备参数,添加多个新增的Request
        for (Hotel hotel : hotels) {
            //转换为文档类型HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //创建新增文档的Request对象
            request.add(new IndexRequest("hotels").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }

小结

  • 文档操作的基本步骤: 初始化RestHighLevelClient
  • 创建XxxRequest。XXX是Index、Get、Update、Delete、Bulk
  • 准备参数(Index、Update、Bulk时需要)
  • 发送请求。调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
  • 解析结果(Get时需要)

十、ElasticSearch查询


elasticsearch的查询依然是基于JSON风格的DSL来实现的。

DSL查询分类

        Elasticsearch提供了基于JSON的DSL(Domain Specific Language)来定义查询。常见的查询类型包括:

查询所有:查询出所有数据,一般测试用(不会显示出所有,自带分页功能)。

例如:

  • match_all

全文检索(full text)查询:利用分词器对用户输入内容分词,然后去倒排索引库中匹配。

例如:

  • match_query:单字段查询
  • multi_match_query:多字段查询,任意一个字段符合条件就算符合查询条件

精确查询:根据精确词条值查找数据,一般是查找keyword、数值、日期、boolean等类型字段。

例如:

  • ids
  • range根据值的范围查询
  • term根据词条精确值查询

地理(geo)查询:根据经纬度查询。

例如:

  • geo_distance
  • geo_bounding_box

复合(compound)查询:复合查询可以将上述各种查询条件组合起来,合并查询条件。例如:

  • bool
  • function_score

RestClient查询文档

文档的查询同样适用RestHighLevelClient对象,基本步骤包括:

  1. 准备Request对象
  2. 准备请求参数
  3. 发起请求
  4. 解析响应

我们以 match_all 查询为例 完整代码如下:

// 查询所有
    @Test
    public void testMatchAll() throws IOException {
        SearchRequest request = new SearchRequest("hotels");
 
        request.source().query(QueryBuilders.matchAllQuery());
 
        SearchResponse response = client.search(request,RequestOptions.DEFAULT);
        show(response);
    }
 
    //查询all字段内容中有如家的(or拼接多条件)
    @Test
    public void testMatch() throws IOException {
        SearchRequest request = new SearchRequest("hotels");
 
        request.source().query(QueryBuilders.matchQuery("all","如家"));
 
        SearchResponse response =  client.search(request,RequestOptions.DEFAULT);
        show(response);
    }
 
    //查询name,business字段内容中有如家的
    @Test
    void testMultiMatch() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotels");
        // 2.准备DSL 参数1:字段  参数2:数据
        request.source()
                .query(QueryBuilders.multiMatchQuery("如家", "name","business"));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        show(response);
    }
 
    // 词条查询
    @Test
    public void testTermQuery() throws IOException{
        SearchRequest request = new SearchRequest("hotels");
 
        request.source().query(QueryBuilders.termQuery("city","上海"));
        SearchResponse response = client.search(request,RequestOptions.DEFAULT);
        show(response);
    }
 
    //范围查询
    @Test
    void testRangeQuery() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotels");
        // 2.准备DSL,QueryBuilders构造查询条件
        request.source()
                .query(QueryBuilders.rangeQuery("price").gte(100).lte(150));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        show(response);
    }
 
    @Test
    void testBool() throws IOException {
        // 1.准备request
        SearchRequest request = new SearchRequest("hotels");
//      布尔查询是一个或多个查询子句的组合,子查询的组合方式有:
//      must:必须匹配每个子查询,类似“与”
//      should:选择性匹配子查询,类似“或”
//      must_not:必须不匹配,不参与算分,类似“非”
//      filter:必须匹配,类似“与”,不参与算分
//        一般搜索框用must,选择条件使用filter
 
        // 2.准备请求参数(and拼接)
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        // 2.1.must
//        boolQuery.must(QueryBuilders.termQuery("city", "上海"));
//        // 2.2.filter小于等于
//        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(260));
//
//        request.source().query(boolQuery);
 
        //方式2
        request.source().query(
                QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("city", "上海"))
                        .filter(QueryBuilders.rangeQuery("price").lte(260))
        );
        // 3.发送请求,得到响应
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.结果解析
        show(response);
    }
 
    @Test
    void testPageAndSort() throws IOException {
        // 页码,每页大小
        int page = 1, size = 20;
        // 查询条件
        String searchName = "如家";
//        String searchName = null;
 
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotels");
        // 2.准备DSL
        // 2.1.query
        if(searchName == null){
            request.source().query(QueryBuilders.matchAllQuery());
        }else{
            request.source().query(QueryBuilders.matchQuery("name", searchName));
        }
        // 2.2.分页 from、size
        request.source().from((page - 1) * size).size(size);
        //2.3.排序
        request.source().sort("price", SortOrder.DESC);
 
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        show(response);
 
    }
 
    // 解析响应对象
    public void show(SearchResponse response){
        // 解析响应
        SearchHits searchHits = response.getHits();
        // 获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜到" + total + "条数据");
        // 文档数组
        SearchHit[] hits = searchHits.getHits();
        // 遍历
        for (SearchHit s : hits){
            String json = s.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
            System.out.println("HotelDoc = " + hotelDoc);
        }
}

十一、web项目实战(Service层):

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {



    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /***********************基础查询***************************/
//    @Override
//    public PageResult search(RequestParams params) {
//        try {
//            // 1.准备Request
//            SearchRequest request = new SearchRequest("hotels");
//            // 2.准备请求参数
//            // 2.1.查询条件
//            String key = params.getKey();
//            if (key == null || "".equals(key)) {
//                request.source().query(QueryBuilders.matchAllQuery());
//            } else {
//                request.source().query(QueryBuilders.matchQuery("all",key));
//            }
//            // 2.2.分页
//            int page = params.getPage();
//            int size = params.getSize();
//            request.source().from((page - 1) * size).size(size);
//            // 3.发送请求
//            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//            // 4.解析响应
//            return handleResponse(response);
//        } catch (IOException e) {
//            throw new RuntimeException("搜索数据失败", e);
//        }
//    }

    /***********************条件查询***************************/
    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotels");
            // 1.准备Boolean查询
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 1.1.关键字搜索,match查询,放到must中
            String key = params.getKey();
            if (key == null || "".equals(key)) {
                // 为空,查询所有
                boolQuery.must(QueryBuilders.matchAllQuery());
            } else {
                // 不为空,根据关键字查询
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }

            // 1.2.品牌
            String brand = params.getBrand();
            if (brand != null) {
                boolQuery.filter(QueryBuilders.termQuery("brand", brand));
            }
            // 1.3.城市
            String city = params.getCity();
            if (city!=null) {
                boolQuery.filter(QueryBuilders.termQuery("city", city));
            }
            // 1.4.星级
            String starName = params.getStarName();
            if (starName!=null) {
                boolQuery.filter(QueryBuilders.termQuery("starName", starName));
            }
            // 1.5.价格范围
            Integer minPrice = params.getMinPrice();
            Integer maxPrice = params.getMaxPrice();
            if (minPrice != null && maxPrice != null) {
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
            }
            // 3.设置查询条件
            request.source().query(boolQuery);
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            PageResult pageResult = handleResponse(response);
            System.out.println(pageResult);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }




    //处理结果集
    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            // 4.4.获取source
            String json = hit.getSourceAsString();
            // 4.5.反序列化,非高亮的
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 4.9.放入集合
            hotels.add(hotelDoc);
            System.out.println(hotelDoc);
        }
        return new PageResult(total, hotels);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值