当前位置:   article > 正文

ElasticSearch搜索引擎_elasticsearch查询索引

elasticsearch查询索引

目录

1.ElasticSearch简介

2.ElasticSearch与MySQL区别

3.ElasticSearch核心概念介绍

3.1索引(Index)

3.1.1添加索引

3.1.2查询索引

3.1.3删除索引

3.2域(Field)

3.2.1数据类型

3.2.2添加映射

3.3文档(Document)

3.3.1添加文档

3.3.2查询文档

3.3.3修改文档

3.3.4删除文档

3.4倒排索引

4.Springboot整合ElasticSearch

4.1批量导入操作

4.2查询操作

4.2.1查询所有

4.2.2分页查询所有

4.2.3精确搜索

4.2.4模糊查询

4.2.5多域搜索

4.2.6搜索提示

4.2.7范围查询

4.2.8多条件查询

4.2.9纠错查询

4.2.10高亮展示

4.2.11加权查询


1.ElasticSearch简介

ElasticSearch是一个开源的、支持分布式的、能够进行近实时搜索和分析、能够处理PB级数据量的搜索引擎。目前有很多平台和工作场景会涉及到对ElasticSearch的使用。

2.ElasticSearch与MySQL区别

  • Mysql数据操作具备事务性,而ElasticSearch没有

  • MySQL支持外键,而ElasticSearch不支持

  • Mysql采用B+树索引,而ElasticSearch采用倒排索引

3.ElasticSearch核心概念介绍

ES在使用时,会涉及到五大核心概念:索引(Index)、映射(Mapping)、域(Field)、文档(Documen)、倒排索引。以一张MySQL中数据表为例:

ElasticSearchMysql
索引(Index)表(Table)
映射(Mapping)表结构
域(Field)字段列(Column)
文档(Document)一条数据(Row)

3.1索引(Index)

索引相当于关系型数据库中的一张表,一个index中包含若干个document,通过index代替一类类似的或相同的document。

3.1.1添加索引

# PUT 索引名称
PUT person

3.1.2查询索引

#查询单个索引 GET 索引名称

GET person

# 查询多个索引信息 GET 索引名称,索引名称
PUT person1
GET person,person1

# 查询所有索引信息
GET _all

3.1.3删除索引

#删除索引 DELETE 索引名称
DELETE person1

3.2域(Field)

域(Field)相当于数据表中的字段列,当有了索引之后,需要在索引中设置域的相关信息如:名称,类型等。这个过程称为:映射(Mapping)。相当于关系型数据库中设置表的信息。

3.2.1数据类型

字符串

  • text:会进行分词,如小米手机,会分成:小米,手机。 被分出来的每一个词,称为term(词条)

  • keyword:不会进行分词,如小米手机,只有一个词条,即小米手机。

数值

  • long:带符号64位整数

  • integer:带符号32位整数

  • short:带符号16位整数

  • byte:带符号8位整数

  • double:双精度64位浮点数

  • float:单精度32位浮点数

  • half_float:半精度16位浮点数

布尔:

  • boolean

二进制:

  • binary

日期:

  • date

范围类型:

  • integer_range

  • float_range

  • long_range

  • double_range

  • date_range

数组

对象

3.2.2添加映射

(1)为已存在的索引库添加映射

PUT person/_mapping
{
  "properties":{
    "name":{
      "type":"text"
    },
    "age":{
      "type":"integer"
    }
  }
}

#查看索引映射信息
GET person/_mapping

(2)创建索引并添加映射

#创建索引并添加映射
PUT person
{
  "mappings": {
    "properties": {
      "name":{
        "type": "text"
      },
      "age":{
        "type": "integer"
      }
    }
  }
}

(3)添加字段

对于映射,只能进行字段添加,不能对字段进行修改或删除,如有需要,则重新创建映射。

#添加字段
PUT person/_mapping
{
  "properties":{
    "name": {
        "type": "text"
      },
      "age": {
        "type": "integer"
      },
      "address":{
        "type":"text"
      }
  }
}

3.3文档(Document)

ES中最小的数据单元,代表索引中的一条数据,通常是使用json的数据格式表示的

3.3.1添加文档

(1)添加文档,手动设置id

#添加文档,手动设置id
POST person/_doc/1
{
  "name":"朱吴",
  "age":"23",
  "address":"南昌"
}

(2)添加文档,自动生成id

#添加文档,自动生成id
POST person/_doc
{
  "name":"朱徐",
  "age":"25",
  "address":"深圳"
}

3.3.2查询文档

(1)根据id查询文档

#GET 索引名称/_doc/文档id
GET person/_doc/1

(2)查询所有文档

#GET 索引名称/_search
GET person/_search

3.3.3修改文档

PUT person/_doc/1
{
  "name":"朱武",
  "age":"26",
  "address":"深圳"
}

3.3.4删除文档

#DELETE 索引名称/_doc/文档id
DELETE person/_doc/1

3.4倒排索引

要想理解倒排索引,首先思考一个问题,获取某个文件夹下所有文件名中包含Spring的文件

1)确定要搜索的文件夹
2)遍历文件夹下所有文件
3)判断文件名中是否包含Spring

这种思维可以理解为是一种正向思维的方式,从外往内,根据key找value。这种方式可以理解为正向索引。

而ElasticSearch为了提升查询效率,采用反向思维方式,根据value找key。

4.Springboot整合ElasticSearch

4.1批量导入操作

索引及映射准备

PUT hotel
{
  "mappings": {
    "properties": {
      
      "name":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "address":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "brand":{
        "type": "keyword"
      },
      "type":{
        "type": "keyword"
      },
       "price":{
        "type": "integer"
      },
      "specs":{
        "type": "keyword"
      },
       "salesVolume":{
        "type": "integer"
      },
      "area":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "imageUrl":{
        "type": "text"
      },
      "synopsis":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "createTime":{
        "type": "date",
        "format": "yyyy-MM-dd"
      },
      "isAd":{
        "type":"integer"
      }
    }
  }
}

在ES中提供了批量操作的方式:例如

#新增一号用户
#删除一号用户
#新增二号用户
POST _bulk
{"create":{"_index":"user","_id":"1"}}
{"name":"张三","age":18,"address":"北京"}
{"delete":{"_index":"user","_id":"1"}}
{"create":{"_index":"user","_id":"2"}}
{"name":"李四","age":20,"address":"黑龙江"}

在代码中,批量导入时,从MySQL中查出所有数据后批量导入ES

  1. //批量导入
  2. @Override
  3. public int addDocToES() {
  4. //todo 批量导入文档实现
  5. // 1.创建批量导入对象
  6. BulkRequest bulkRequest = new BulkRequest();
  7. //2.从MySQL数据库中查出所有数据
  8. List<HotelEntity> hotelList = hotelMapper.selectList(null);
  9. //3.遍历,使用带有转换日期的JSON序列化并将数据加入到创建的导入对象中
  10. for (HotelEntity hotelEntity : hotelList) {
  11. //3.1将实体进行序列化
  12. String data = JSON.toJSONStringWithDateFormat(hotelEntity, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
  13. //3.2 实例化IndexRequest并设置索引名,文档内容(对象的JSON格式)
  14. IndexRequest indexRequest = new IndexRequest("hotel").source(data, XContentType.JSON);
  15. //3.3加入批量批量导入对象中
  16. bulkRequest.add(indexRequest);
  17. }
  18. try {
  19. //4.通过restHighLevelClient调用bulk方法,开启执行批量操作
  20. BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
  21. return responses.status().getStatus();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. return 0;
  26. }

4.2查询操作

4.2.1查询所有

GET hotel/_search
{
  "query": {
    "match_all": {}
  }
}

  1. //查询全部
  2. /*
  3. GET hotel/_search
  4. {
  5. "query": {
  6. "match_all": {}
  7. }
  8. }
  9. */
  10. @Override
  11. public Map<String, Object> matchAllQuery() {
  12. //todo 查询全部文档实现
  13. //1.创建搜索请求对象SearchRequest
  14. SearchRequest searchRequest = new SearchRequest("hotel");
  15. //2.创建searchSourceBuilder,进行筛选条件填充
  16. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  17. //2.1构建查询方式
  18. QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
  19. searchSourceBuilder.query(queryBuilder);
  20. searchRequest.source(searchSourceBuilder);
  21. //3.通过restHighLevelClient调用search方法,开启查询
  22. try {
  23. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  24. //4.处理查询结果
  25. //4.1获取查询结果
  26. SearchHits hits = searchResponse.getHits();
  27. long totalHits = hits.getTotalHits().value;
  28. SearchHit[] hits1 = hits.getHits();
  29. //4.2,反序列化后添加到集合中
  30. List<HotelEntity>list = new ArrayList<>();
  31. for (SearchHit searchHit : hits1) {
  32. String sourceAsString = searchHit.getSourceAsString();
  33. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  34. }
  35. //4.3封装成map
  36. Map<String,Object> map = new HashMap<>();
  37. map.put("list",list);
  38. map.put("totalResultSize",totalHits);
  39. return map;
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }
4.2.2分页查询所有

GET hotel/_search
{
  "query": {
    "match_all": {}
  },
  "from": 0,
  "size": 5
}

  1. public Map<String, Object> pageQuery(int current, int size) {
  2. //todo 分页查询文档实现
  3. //1.创建搜索请求对象SearchRequest
  4. SearchRequest searchRequest = new SearchRequest("hotel");
  5. //2.创建SearchSourceBuilder,进行筛选条件填充
  6. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  7. //2.1构建查询方式
  8. MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
  9. searchSourceBuilder.query(queryBuilder);
  10. //2.2设置分页
  11. searchSourceBuilder.from((current-1)*size);
  12. searchSourceBuilder.size(size);
  13. searchRequest.source(searchSourceBuilder);
  14. //3.执行查询
  15. try {
  16. SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
  17. //4.处理查询结果
  18. SearchHits searchHits = searchResponse.getHits();
  19. long hitsTotal = searchHits.getTotalHits().value;
  20. SearchHit[] hits = searchHits.getHits();
  21. List<HotelEntity> list = new ArrayList<>();
  22. for (SearchHit searchHit : hits){
  23. String sourceAsString = searchHit.getSourceAsString();
  24. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  25. }
  26. Map<String, Object> map = new HashMap<>();
  27. map.put("list", list);
  28. map.put("totalResultSize", hitsTotal);
  29. map.put("current", current);
  30. //设置总页数
  31. map.put("totalPage",(hitsTotal+size-1)/size);
  32. return map;
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. return null;
  37. }
4.2.3精确搜索

termQuery:不会对查询条件进行分词(keyword)

GET hotel/_search
{
  "query": {
    "term": {
      "brand": {
        "value": "万豪"
      }
    }
  }
}
GET hotel/_search
{
  "query": {
    "term": {
      "brand": "万豪"
    }
  }
}

  1. public Map<String, Object> brandTermQuery(int current, int size, Map<String, Object> searchParam) {
  2. //todo 按品牌精确查询实现
  3. //1.构建查询请求对象SearchRequest
  4. SearchRequest searchRequest = new SearchRequest("hotel");
  5. //2.创建SearchSourceBuilder,进行筛选条件填充
  6. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  7. //2.1构建查询方式
  8. if(!StringUtils.isEmpty(searchParam.get("brand"))){
  9. QueryBuilder queryBuilder = QueryBuilders.termQuery("brand", searchParam.get("brand").toString());
  10. searchSourceBuilder.query(queryBuilder);
  11. }
  12. //2.2设置分页
  13. searchSourceBuilder.from((current - 1)*size);
  14. searchSourceBuilder.size(size);
  15. searchRequest.source(searchSourceBuilder);
  16. //3.执行查询
  17. try {
  18. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  19. //4.处理查询结果
  20. SearchHits searchHits = searchResponse.getHits();
  21. long hitsTotal = searchHits.getTotalHits().value;
  22. SearchHit[] hits = searchHits.getHits();
  23. List<HotelEntity> list = new ArrayList<>();
  24. for (SearchHit hit : hits) {
  25. String sourceAsString = hit.getSourceAsString();
  26. list.add(JSON.parseObject(sourceAsString, HotelEntity.class));
  27. }
  28. //5.封装返回结果
  29. Map<String,Object> map = new HashMap<>();
  30. map.put("list",list);
  31. map.put("totalResultSize",hitsTotal);
  32. map.put("current",current);
  33. //6.设置总页数
  34. map.put("totalPage",(hitsTotal+size-1)/size);
  35. return map;
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }

4.2.3分词匹配查询

GET hotel/_search
{
  "query": {
    "match": {
     "name":"北京市东城区万豪酒店"
    }
  }
}

  1. public Map<String, Object> nameMatchQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //todo 根据酒店名称匹配查询实现
  3. //1.构建查询请求对象
  4. SearchRequest searchRequest = new SearchRequest("hotel");
  5. //2.创建SearchSourceBuilder,进行筛选条件填充
  6. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  7. //3.查询条件构造
  8. MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", searchParam.get("name"));
  9. searchSourceBuilder.query(queryBuilder);
  10. //4.设置分页
  11. searchSourceBuilder.from((current-1)*size);
  12. searchSourceBuilder.size(size);
  13. searchRequest.source(searchSourceBuilder);
  14. try {
  15. //5.执行查询
  16. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  17. //6.处理查询结果
  18. SearchHits searchHits = searchResponse.getHits();
  19. //6.1命中结果总数
  20. long hitsTotal = searchHits.getTotalHits().value;
  21. SearchHit[] hits = searchHits.getHits();
  22. List<HotelEntity> list = new ArrayList<>();
  23. for (SearchHit hit : hits) {
  24. String sourceAsString = hit.getSourceAsString();
  25. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  26. }
  27. //6.2.封装返回结果
  28. Map<String,Object> map = new HashMap<>();
  29. map.put("list",list);
  30. map.put("totalResultSize",hitsTotal);
  31. map.put("current",current);
  32. //6.3.设置总页数
  33. map.put("totalPage",(hitsTotal+size-1)/size);
  34. return map;
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. return null;
  39. }
4.2.4模糊查询

wildcardQuery:会对查询条件进行分词。还可以使用通配符 ?(任意单个字符) 和 * (0个或多个字符)

GET hotel/_search
{
  "query": {
    "wildcard": {
      "brand": {
        "value": "美*"
      }
    }
  }
}

  1. public Map<String, Object> nameWildcardQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //todo 根据酒店名称模糊查询
  3. //1.构建查询对象searchRequest
  4. SearchRequest searchRequest = new SearchRequest("hotel");
  5. //2.构造searchSourceBuilder,构造DSL
  6. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  7. WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery("brand", searchParam.get("name") + "*");
  8. sourceBuilder.query(queryBuilder);
  9. //3.设置分页
  10. sourceBuilder.from((current-1)*size);
  11. sourceBuilder.size(size);
  12. searchRequest.source(sourceBuilder);
  13. try {
  14. //4.执行查询
  15. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  16. //5.处理查询结果
  17. SearchHits searchHits = searchResponse.getHits();
  18. long hitsTotal = searchHits.getTotalHits().value;
  19. SearchHit[] hits = searchHits.getHits();
  20. List<HotelEntity> list = new ArrayList<>();
  21. for (SearchHit hit : hits) {
  22. String sourceAsString = hit.getSourceAsString();
  23. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  24. }
  25. //6.封装返回信息
  26. Map<String,Object> map = new HashMap<>();
  27. map.put("list",list);
  28. map.put("totalResultSize", hitsTotal);
  29. map.put("current", current);
  30. //设置总页数
  31. map.put("totalPage", (hitsTotal + size - 1) / size);
  32. return map;
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. return null;
  37. }
4.2.5多域搜索

queryStringQuery

•会对查询条件进行分词。

•然后将分词后的查询条件和词条进行等值匹配

•默认取并集(OR)

•可以指定多个查询字段

GET hotel/_search
{
  "query": {
    "query_string": {
      "fields": ["name","synopsis","area","address"],
      "query": "如心 OR spa"
    }
  }
}

  1. public Map<String, Object> searchQueryStringQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //构建查询对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //构建searchSourceBuilder,设置DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. //根据name,synopsis,area,address进行多域查询
  7. QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(searchParam.get("condition").toString())
  8. .field("name")
  9. .field("synopsis")
  10. .field("area")
  11. .field("address")
  12. .defaultOperator(Operator.OR);
  13. searchSourceBuilder.query(queryBuilder);
  14. //设置分页
  15. searchSourceBuilder.from((current-1)*size);
  16. searchSourceBuilder.size(size);
  17. searchRequest.source(searchSourceBuilder);
  18. try {
  19. //执行查询
  20. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  21. //处理查询结果
  22. SearchHits searchHits = searchResponse.getHits();
  23. long totalHits = searchHits.getTotalHits().value;
  24. SearchHit[] hits = searchHits.getHits();
  25. List<HotelEntity> list = new ArrayList<>();
  26. for (SearchHit hit : hits) {
  27. String sourceAsString = hit.getSourceAsString();
  28. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  29. }
  30. //封装返回信息
  31. Map<String,Object> map = new HashMap<>();
  32. map.put("list", list);
  33. map.put("totalResultSize", totalHits);
  34. map.put("current", current);
  35. //设置总页数
  36. map.put("totalPage", (totalHits + size - 1) / size);
  37. return map;
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. return null;
  42. }
4.2.6搜索提示

(1)新建用于存储用户搜索记录的索引库

PUT suggest
{
  "mappings": {
    "properties": {
      "name":{
        "type": "completion",
        "analyzer": "ik_max_word"
      }
    }
  }    
}

(2)数据查询

GET suggest/_search
{
  "suggest": {
    "my-suggest": {
      "prefix": "酒店环境",
      "completion": {
        "field": "name",
        "size":10
      }
    }
  }
}

GET suggest/_search
{
  "suggest": {
    "my-suggest": {
      "prefix": "酒店",
      "completion": {
        "field": "name",
        "size":10
      }
    }
  }
}

  1. public List<String> searchSuggestInfo(String key) {
  2. //定义结果集
  3. List<String> result = new ArrayList<>();
  4. //构建查询对象
  5. SearchRequest searchRequest = new SearchRequest("suggest");
  6. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  7. //构建自动补全搜索
  8. SuggestBuilder suggestBuilder = new SuggestBuilder();
  9. CompletionSuggestionBuilder suggestion= SuggestBuilders.completionSuggestion("name").text(key).size(10);
  10. suggestBuilder.addSuggestion("my-suggest",suggestion);
  11. searchSourceBuilder.suggest(suggestBuilder);
  12. searchRequest.source(searchSourceBuilder);
  13. try {
  14. //执行查询
  15. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  16. //处理自动补全查询结果
  17. Suggest suggest = searchResponse.getSuggest();
  18. CompletionSuggestion completionSuggestion = suggest.getSuggestion("my-suggest");
  19. List<CompletionSuggestion.Entry> entries = completionSuggestion.getEntries();
  20. Map<String, Object> map = new HashMap<>();
  21. if (entries!=null && entries.size()>0){
  22. entries.forEach(entry -> {
  23. if (!ObjectUtils.isEmpty(entry.getOptions())){
  24. entry.forEach(action -> {
  25. String suggestInfo = action.getText().toString();
  26. if (suggestInfo.equals(key)){
  27. return;
  28. }
  29. result.add(suggestInfo);
  30. });
  31. }else {
  32. map.put("name",key);
  33. }
  34. });
  35. }
  36. //向索引库增量添加查询条件
  37. if (!ObjectUtils.isEmpty(map)) {
  38. IndexRequest indexRequest = new IndexRequest("suggest").source(map);
  39. restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
  40. }
  41. System.out.println("list" + result);
  42. return result;
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. return null;
  47. }

4.2.7排序查询

#降序
GET hotel/_search
{
  "sort": [
    {
      "salesVolume": {
        "order": "desc"
      }
    }
  ]
}

#升序
GET hotel/_search
{
  "sort": [
    {
      "salesVolume": {
        "order": "asc"
      }
    }
  ]
}

  1. public Map<String, Object> salesSortQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //构建查询请求对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //构建SearchSourceBuilder,构建DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. if ("desc".equalsIgnoreCase(searchParam.get("sortWay").toString())){
  7. searchSourceBuilder.sort("salesVolume", SortOrder.DESC);
  8. }else {
  9. searchSourceBuilder.sort("salesVolume",SortOrder.ASC);
  10. }
  11. //设置分页
  12. searchSourceBuilder.from((current-1)*size);
  13. searchSourceBuilder.size(size);
  14. searchRequest.source(searchSourceBuilder);
  15. try {
  16. //执行查询
  17. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  18. //处理查询结果
  19. SearchHits searchHits = searchResponse.getHits();
  20. long totalHits = searchHits.getTotalHits().value;
  21. SearchHit[] hits = searchHits.getHits();
  22. List<HotelEntity> list = new ArrayList<>();
  23. for (SearchHit hit : hits) {
  24. String sourceAsString = hit.getSourceAsString();
  25. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  26. }
  27. //map封装
  28. Map<String,Object> map = new HashMap<>();
  29. map.put("list",list);
  30. map.put("totalResultSize", totalHits);
  31. map.put("current", current);
  32. //设置总页数
  33. map.put("totalPage", (totalHits + size - 1) / size);
  34. map.put("sortWay",searchParam.get("sortWay"));
  35. return map;
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
4.2.7范围查询

GET hotel/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 500,
        "lte": 2000
      }
    }
  }
}

  1. public Map<String, Object> priceRangeQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //创建查询请求对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //创建SearchSourceBuilder,设置DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("price")
  7. .gte(searchParam.get("minPrice"))
  8. .lte(searchParam.get("maxPrice"));
  9. searchSourceBuilder.query(queryBuilder);
  10. //设置分页
  11. searchSourceBuilder.from((current-1)*size);
  12. searchSourceBuilder.size(size);
  13. searchRequest.source(searchSourceBuilder);
  14. try {
  15. //执行查询
  16. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  17. //处理查询结果
  18. SearchHits searchHits = searchResponse.getHits();
  19. long totalHits = searchHits.getTotalHits().value;
  20. SearchHit[] hits = searchHits.getHits();
  21. List<HotelEntity>list = new ArrayList<>();
  22. for (SearchHit hit : hits) {
  23. String sourceAsString = hit.getSourceAsString();
  24. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  25. }
  26. //map封装
  27. Map<String,Object> map = new HashMap<>();
  28. map.put("list",list);
  29. map.put("totalResultSize", totalHits);
  30. map.put("current", current);
  31. //设置总页数
  32. map.put("totalPage", (totalHits + size - 1) / size);
  33. map.put("minPrice", searchParam.get("minPrice"));
  34. map.put("maxPrice", searchParam.get("maxPrice"));
  35. return map;
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
4.2.8多条件查询

boolQuery:对多个查询条件连接。

连接方式:

must(and):条件必须成立

must_not(not):条件必须不成立

should(or):条件可以成立

filter:条件必须成立,性能比must高。

#must单独使用 品牌必须是万豪,地区必须是北京
GET hotel/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "brand": {
              "value": "万豪"
            }
          }
        },
        {
          "term": {
            "area": {
              "value": "北京市"
            }
          }
        }
      ]
    }
  }
}

# must与filter组合使用 查询品牌为万豪下的,区域为北京,价格范围在500和2000之间的酒店
GET hotel/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "brand": {
              "value": "万豪"
            }
          }
        }
      ],
      "filter":[ 
        {
        "term": {
          "area": "北京市"
        }
       },
       {
         "range":{
          "price": {
            "gte": 500,
            "lte": 2000
         }
         }
       }
      ]
    }
  }
}

#filter 单独使用   filter可以是单个条件,也可多个条件(数组形式)
GET hotel/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "brand": {
              "value": "万豪"
            }
          }
        }
      ]
    }
  }
}

  1. public Map<String, Object> searchBoolQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //创建查询请求对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //创建 SearchSourceBuilder 对象,设置DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. //多条件查询 :多域、品牌精确、城市精确、星级精确、价格范围、销量排序
  7. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  8. //多域
  9. if(!ObjectUtils.isEmpty(searchParam.get("condition"))){
  10. QueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(searchParam.get("condition").toString())
  11. .field("name")
  12. .field("synopsis")
  13. .field("area")
  14. .field("address")
  15. .defaultOperator(Operator.OR);
  16. boolQueryBuilder.must(queryStringQueryBuilder);
  17. }
  18. //品牌精准
  19. if(ObjectUtils.isNotEmpty(searchParam.get("brand"))){
  20. QueryBuilder termQueryBuilder = QueryBuilders.termQuery("brand", searchParam.get("brand"));
  21. boolQueryBuilder.filter(termQueryBuilder);
  22. }
  23. //城市精确
  24. if (ObjectUtils.isNotEmpty(searchParam.get("area"))) {
  25. QueryBuilder termQueryBuilder = QueryBuilders.termQuery("area", searchParam.get("area"));
  26. boolQueryBuilder.filter(termQueryBuilder);
  27. }
  28. //星级精确
  29. if (ObjectUtils.isNotEmpty(searchParam.get("specs"))) {
  30. QueryBuilder termQueryBuilder = QueryBuilders.termQuery("specs", searchParam.get("specs"));
  31. boolQueryBuilder.filter(termQueryBuilder);
  32. }
  33. //价格范围
  34. if(ObjectUtils.isNotEmpty(searchParam.get("minPrice")) && !StringUtils.isEmpty(searchParam.get("maxPrice"))){
  35. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price")
  36. .gte(searchParam.get("minPrice"))
  37. .lte(searchParam.get("maxPrice"));
  38. boolQueryBuilder.filter(rangeQueryBuilder);
  39. }
  40. //销量排序
  41. if (ObjectUtils.isNotEmpty(searchParam.get("sortWay"))){
  42. if("desc".equalsIgnoreCase(searchParam.get("sortWay").toString())){
  43. searchSourceBuilder.sort("salesVolume",SortOrder.DESC);
  44. }else {
  45. searchSourceBuilder.sort("salesVolume",SortOrder.ASC);
  46. }
  47. }
  48. searchSourceBuilder.query(boolQueryBuilder);
  49. //设置分页
  50. searchSourceBuilder.from((current-1)*size);
  51. searchSourceBuilder.size(size);
  52. searchRequest.source(searchSourceBuilder);
  53. try {
  54. //执行查询
  55. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  56. //处理查询结果
  57. SearchHits searchHits = searchResponse.getHits();
  58. long totalHits = searchHits.getTotalHits().value;
  59. SearchHit[] hits = searchHits.getHits();
  60. List<HotelEntity> list = new ArrayList<>();
  61. for (SearchHit hit : hits) {
  62. String sourceAsString = hit.getSourceAsString();
  63. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  64. }
  65. Map<String, Object> map = new HashMap<>();
  66. map.put("list", list);
  67. map.put("totalResultSize", totalHits);
  68. map.put("current", current);
  69. //设置总页数
  70. map.put("totalPage", (totalHits + size - 1) / size);
  71. map.put("brand", searchParam.get("brand"));
  72. map.put("area", searchParam.get("area"));
  73. map.put("specs", searchParam.get("specs"));
  74. map.put("sortWay", searchParam.get("sortWay"));
  75. map.put("minPrice", searchParam.get("minPrice"));
  76. map.put("maxPrice", searchParam.get("maxPrice"));
  77. return map;
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. }
  81. return null;
  82. }
4.2.9纠错查询

fuzzyQuery

​ 自动纠错查询,会自动尝试将搜索条件进行纠错,然后去跟term进行匹配。

  • fuzziness:查询允许的最大编辑距离,默认为0

  • prefix_length:设置前几个字符不允许编辑

GET hotel/_search
{
  "query": {
    "fuzzy": {
      "area": {
        "value": "北经市",
        "fuzziness": 1,
        "prefix_length": 1
      }
    }
  }
}

4.2.10高亮展示

如需将搜索条件以高亮形式展示,则需要在查询时,设置需要对哪一个域进行高亮展示

fields:指定要对哪个域高亮显示

pre_tags:设置高亮样式前缀

post_tags:设置高亮样式后缀

GET hotel/_search
{
  "query": {
    "term": {
      "name": {
        "value": "北京市"
      }
    }
  },
  "highlight": {
    "fields": {
      "name": {
        "pre_tags": "<font color = 'red'>",
        "post_tags": "</font>"
      }
    }
  }
}

  1. public Map<String, Object> searchHighLight(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //创建查询请求对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //创建SearchSourceBuilder对象,设置查询条件DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. if (ObjectUtils.isNotEmpty(searchParam.get("condition"))){
  7. QueryBuilder queryBuilder = QueryBuilders.termQuery("name", searchParam.get("condition"));
  8. searchSourceBuilder.query(queryBuilder);
  9. }
  10. //设置分页
  11. searchSourceBuilder.from((current - 1) * size);
  12. searchSourceBuilder.size(size);
  13. //设置高亮显示
  14. HighlightBuilder highlightBuilder = new HighlightBuilder();
  15. highlightBuilder.field("name");
  16. highlightBuilder.preTags("<font color = 'red'>");
  17. highlightBuilder.postTags("</font>");
  18. searchSourceBuilder.highlighter(highlightBuilder);
  19. searchRequest.source(searchSourceBuilder);
  20. try {
  21. //执行查询
  22. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  23. //处理查询结果
  24. SearchHits searchHits = searchResponse.getHits();
  25. long totalHits = searchHits.getTotalHits().value;
  26. SearchHit[] hits = searchHits.getHits();
  27. List<HotelEntity> list = new ArrayList<>();
  28. for (SearchHit hit : hits){
  29. String sourceAsString = hit.getSourceAsString();
  30. HotelEntity hotelEntity = JSON.parseObject(sourceAsString, HotelEntity.class);
  31. //处理高亮结果
  32. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  33. HighlightField highlightField = highlightFields.get("name");
  34. if (highlightField!=null){
  35. Text[] fragments = highlightField.getFragments();
  36. hotelEntity.setName(fragments[0].toString());
  37. }
  38. list.add(hotelEntity);
  39. }
  40. Map<String, Object> map = new HashMap<>();
  41. map.put("list", list);
  42. map.put("totalResultSize", totalHits);
  43. map.put("current", current);
  44. //设置总页数
  45. map.put("totalPage", (totalHits + size - 1) / size);
  46. return map;
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. return null;
  51. }
4.2.11加权查询

权重设置的两种方式:索引设置,查询设置

索引设置:不常用,因为随着业务的改变,要设置权重的域也会发生改变,而索引一旦创建则无法修改,除非删除索引重建。

索引设置:

PUT hotel
{
  "mappings": {
    "properties": {
      
      "name":{
        "type": "text",
        "analyzer": "ik_max_word",
        "boost": 5
      },
      "address":{
        "type": "text",
        "analyzer": "ik_max_word",
        "boost": 3
      }
    }
  }
}

查询设置:

该方式在开发中很常用,根据业务条件需求,在查询时灵活的配置权重。

​ 在下列查询中,query中的内容为主查询条件,functions中为判断要为哪些数据加权。weight为加权值。

GET hotel/_search
{
  "query": {
    "function_score": {
      "query": {
        "query_string": {
          "fields": ["name","synopsis","area","address"],
          "query": "北京市万豪spa三星"
        }
      },
      "functions": [
        {
          "filter": {
            "term": {
              "isAd": "1"
            }
          },
          "weight": 100
        }
      ]
    }
  }
}

  1. public Map<String, Object> searchScoreQuery(Integer current, Integer size, Map<String, Object> searchParam) {
  2. //创建查询请求对象
  3. SearchRequest searchRequest = new SearchRequest("hotel");
  4. //创建SearchSourceBuilder,设置DSL
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  6. QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(searchParam.get("condition").toString())
  7. .field("name")
  8. .field("synopsis")
  9. .field("area")
  10. .field("address")
  11. .defaultOperator(Operator.OR);
  12. //构建加权条件
  13. FunctionScoreQueryBuilder.FilterFunctionBuilder[] scoreFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
  14. new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAd", 1), ScoreFunctionBuilders.weightFactorFunction(100))
  15. };
  16. FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(queryStringQueryBuilder, scoreFunctionBuilders);
  17. searchSourceBuilder.query(queryBuilder);
  18. //设置分页
  19. searchSourceBuilder.from((current-1)*size);
  20. searchSourceBuilder.size(size);
  21. searchRequest.source(searchSourceBuilder);
  22. try {
  23. //执行查询
  24. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  25. SearchHits searchHits = searchResponse.getHits();
  26. long totalHits = searchHits.getTotalHits().value;
  27. SearchHit[] hits = searchHits.getHits();
  28. List<HotelEntity> list = new ArrayList<>();
  29. for (SearchHit hit : hits) {
  30. String sourceAsString = hit.getSourceAsString();
  31. list.add(JSON.parseObject(sourceAsString,HotelEntity.class));
  32. }
  33. Map<String, Object> map = new HashMap<>();
  34. map.put("list", list);
  35. map.put("totalResultSize", totalHits);
  36. map.put("current", current);
  37. //设置总页数
  38. map.put("totalPage", (totalHits + size - 1) / size);
  39. return map;
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/1005846
推荐阅读
相关标签
  

闽ICP备14008679号