ElasticSearch高级操作

一、批量操作

1、脚本形式

例:
#删除5号
#新增8号
#更新2号 name为2号

POST _bulk
{"delete":{"_index":"person1","_id":"5"}}
{"create":{"_index":"person1","_id":"8"}}
{"name":"八号","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2号"}}

2、java操作

//创建bulkrequest对象,整合所有操作
BulkRequest bulkRequest =new BulkRequest();
/*
# 1. 删除5号记录
# 2. 添加6号记录
# 3. 修改3号记录 名称为 “三号”
*/
//1. 删除5号记录
DeleteRequest deleteRequest=new DeleteRequest("person1","5");
bulkRequest.add(deleteRequest);

//2. 添加6号记录
Map map=new HashMap<>();
map.put("name","六号");
IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
bulkRequest.add(indexRequest);

//3. 修改3号记录 名称为 “三号”
Map mapUpdate=new HashMap<>();
mapUpdate.put("name","三号");
UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);
bulkRequest.add(updateRequest);

//执行批量操作
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());

 3、从数据库写入数据

//1.查询所有数据,mysql
List goodsList = goodsMapper.findAll();

//2.bulk导入
BulkRequest bulkRequest=new BulkRequest();

//2.1 循环goodsList,创建IndexRequest添加数据
for (Goods goods : goodsList) {
    //2.2 设置spec规格信息 Map的数据   specStr:{}
    String specStr = goods.getSpecStr();
    //将json格式字符串转为Map集合
    Map map = JSON.parseObject(specStr, Map.class);
    //设置spec map
    goods.setSpec(map);
    //将goods对象转换为json字符串
    String data = JSON.toJSONString(goods);
    IndexRequest indexRequest=new IndexRequest("goods").source(data,XContentType.JSON);
    bulkRequest.add(indexRequest);
}
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());

二、高级查询操作

1、matchAll查询

脚本:

GET goods/_search
{
  "query": {
    "match_all": {}
  },
  "from": 0,
  "size": 20
}

java:

//构建查询请求对象,指定查询的索引名称
SearchRequest searchRequest=new SearchRequest("goods");
//创建查询条件构建器SearchSourceBuilder
SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
//查询条件
QueryBuilder queryBuilder= QueryBuilders.matchAllQuery();
//指定查询条件
sourceBuilder.query(queryBuilder);
//添加分页信息  不设置 默认10条
sourceBuilder.from(0);
sourceBuilder.size(20);
//添加查询条件构建器 SearchSourceBuilder
searchRequest.source(sourceBuilder);
//查询,获取查询结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//1、获取命中对象 SearchHits
SearchHits hits = searchResponse.getHits();
//1.1 获取总记录数
Long total= hits.getTotalHits().value;
System.out.println("总数:"+total);
//1.2 获取Hits数据  数组
SearchHit[] hits1 = hits.getHits();
//获取json字符串格式的数据
List goodsList = new ArrayList<>();
for (SearchHit searchHit : hits1) {
    String sourceAsString = searchHit.getSourceAsString();
    //转为java对象
    Goods goods = JSON.parseObject(sourceAsString, Goods.class);
    goodsList.add(goods);
}
for (Goods goods : goodsList) {
    System.out.println(goods);
}

2、termQuery词条查询

term查询:不会对查询条件进行分词。

脚本:

GET goods/_search
{
  "query": {
    "term": {
      "title": {
        "value": "华为"
      }
    }
  }
}

java:

//构建查询请求对象,指定查询的索引名称
SearchRequest searchRequest=new SearchRequest("goods");
//创建查询条件构建器SearchSourceBuilder
SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
//查询条件
QueryBuilder queryBuilder= QueryBuilders.termQuery("title","华为");
//指定查询条件
sourceBuilder.query(queryBuilder);
//添加查询条件构建器 SearchSourceBuilder
searchRequest.source(sourceBuilder);
//查询,获取查询结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

3、matchQuery查询

match查询:

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

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

•默认取并集(OR),也可指定交集(AND)

脚本:

GET goods/_search
{
  "query": {
    "match": {
      "title": {
                "query": "华为手机",
                "operator": "and"
        }
    }
  }
}

 java:

//构建查询请求对象,指定查询的索引名称
SearchRequest searchRequest=new SearchRequest("goods");
//创建查询条件构建器SearchSourceBuilder
SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
//查询条件
MatchQueryBuilder queryBuilder= QueryBuilders.matchQuery("title","华为");
queryBuilder.operator(Operator.AND);
//指定查询条件
sourceBuilder.query(queryBuilder);
//添加查询条件构建器 SearchSourceBuilder
searchRequest.source(sourceBuilder);
//查询,获取查询结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

4、模糊查询

脚本:

(1)wildcard查询

"*华*"  包含华字的
"华*"   华字后边多个字符
"华?"  华字后边1个字符
"*华"或"?华" 会引发全表(全索引)扫描 注意效率问题

GET goods/_search
{
  "query": {
    "wildcard": {
      "title": {
        "value": "华*"
      }
    }
  }
}

(2)正则查询

GET goods/_search
{
  "query": {
    "regexp": {
      "title": "\\w+(.)*"
    }
  }
}

(3)前缀查询

GET goods/_search
{
  "query": {
    "prefix": {
      "brandName": {
        "value": "三"
      }
    }
  }
}

java:

//模糊查询
WildcardQueryBuilder query = QueryBuilders.wildcardQuery("title", "华*");//华后多个字符
//正则查询
RegexpQueryBuilder query = QueryBuilders.regexpQuery("title", "\\w+(.)*");
//前缀查询
PrefixQueryBuilder query = QueryBuilders.prefixQuery("brandName", "三");

 5、范围与排序查询

脚本:

GET goods/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 2000,
        "lte": 3000
      }
    }
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}

java:

//范围查询 以price 价格为条件
RangeQueryBuilder query = QueryBuilders.rangeQuery("price");

//指定下限
query.gte(2000);
//指定上限
query.lte(3000);

sourceBuilder.query(query);

//排序  价格 降序排列
sourceBuilder.sort("price",SortOrder.DESC);

6、queryString多字段查询

queryString 多条件查询

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

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

•默认取并集(OR)

•可以指定多个查询字段

query_string:识别query中的连接符(or 、and)

GET goods/_search
{
  "query": {
    "query_string": {
      "fields": ["title","categoryName","brandName"], 
      "query": "华为 AND 手机"
    }
  }
}

simple_query_string:不识别query中的连接符(or 、and),查询时会将 “华为”、"and"、“手机”分别进行查询

GET goods/_search
{
  "query": {
    "simple_query_string": {
      "fields": ["title","categoryName","brandName"], 
      "query": "华为 AND 手机"
    }
  }
}

java:

QueryStringQueryBuilder query = QueryBuilders.queryStringQuery("华为手机").field("title").field("categoryName")
.field("brandName").defaultOperator(Operator.AND);

7、布尔查询

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

•must(and):条件必须成立

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

•should(or):条件可以成立

•filter:条件必须成立,性能比must高。不会计算得分

得分:即条件匹配度,匹配度越高,得分越高

GET goods/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "brandName": {
              "value": "华为"
            }
          }
        }
      ],
      "filter":[ 
        {
        "term": {
          "title": "手机"
        }
       },
       {
         "range":{
             "price": {
                "gte": 2000,
                "lte": 3000
             }
         }
       }
      ]
    }
  }
}

java:

//1.构建boolQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//2.构建各个查询条件
//2.1 查询品牌名称为:华为
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "华为");
boolQuery.must(termQueryBuilder);
//2.2. 查询标题包含:手机
MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", "手机");
boolQuery.filter(matchQuery);
//2.3 查询价格在:2000-3000
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
rangeQuery.gte(2000);
rangeQuery.lte(3000);
boolQuery.filter(rangeQuery);
sourceBuilder.query(boolQuery);

 8、聚合查询

指标聚合:相当于MySQL的聚合函数。max、min、avg、sum等

桶聚合:相当于MySQL的 group by 操作。不要对text类型的数据进行分组,会失败。

//指标聚合 聚合函数

GET goods/_search
{
  "query": {
    "match": {
      "title": "手机"
    }
  },
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}

//桶聚合  分组

GET goods/_search
{
  "query": {
    "match": {
      "title": "手机"
    }
  },
  "aggs": {
    "goods_brands": {
      "terms": {
        "field": "brandName",
        "size": 100
      }
    }
  }
}

java:

/**
* 聚合查询:桶聚合,分组查询
* 1. 查询title包含手机的数据
* 2. 查询品牌列表
*/
//1. 查询title包含手机的数据
MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "手机");
sourceBuilder.query(queryBuilder);
//2. 查询品牌列表  只展示前100条
AggregationBuilder  
    aggregation=AggregationBuilders.terms("goods_brands").field("brandName").size(100);
sourceBuilder.aggregation(aggregation);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//7. 获取命中对象 SearchHits
SearchHits hits = searchResponse.getHits();
//7.1 获取总记录数
Long total= hits.getTotalHits().value;
System.out.println("总数:"+total);
// aggregations 对象
Aggregations aggregations = searchResponse.getAggregations();
//将aggregations 转化为map
Map aggregationMap = aggregations.asMap();
//通过key获取goods_brands 对象 使用Aggregation的子类接收  buckets属性在Terms接口中体现
//Aggregation goods_brands1 = aggregationMap.get("goods_brands");
Terms goods_brands =(Terms) aggregationMap.get("goods_brands");
//获取buckets 数组集合
List buckets = goods_brands.getBuckets();
Mapmap=new HashMap<>();
//遍历buckets   key 属性名,doc_count 统计聚合数
for (Terms.Bucket bucket : buckets) {
    System.out.println(bucket.getKey());
    map.put(bucket.getKeyAsString(),bucket.getDocCount());
}
System.out.println(map);

9、高亮查询

高亮三要素:

•高亮字段

•前缀

•后缀

默认前后缀 :em

GET goods/_search
{
  "query": {
    "match": {
      "title": "电视"
    }
  },
  "highlight": {
    "fields": {
      "title": {
        "pre_tags": "",
        "post_tags": ""
      }
    }
  }
}

java:1. 设置高亮 高亮字段 前缀 后缀   2. 将高亮了的字段数据,替换原有数据

// 1. 查询title包含手机的数据
    MatchQueryBuilder query = QueryBuilders.matchQuery("title", "手机");

    sourceBulider.query(query);

    //设置高亮
    HighlightBuilder highlighter = new HighlightBuilder();
    //设置三要素
    highlighter.field("title");
    //设置前后缀标签
    highlighter.preTags("");
    highlighter.postTags("");

    //加载已经设置好的高亮配置
    sourceBulider.highlighter(highlighter);

    searchRequest.source(sourceBulider);

    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);


    SearchHits searchHits = searchResponse.getHits();
    //获取记录数
    long value = searchHits.getTotalHits().value;
    System.out.println("总记录数:"+value);

    List goodsList = new ArrayList<>();
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        String sourceAsString = hit.getSourceAsString();

        //转为java
        Goods goods = JSON.parseObject(sourceAsString, Goods.class);

        // 获取高亮结果,替换goods中的title
        Map highlightFields = hit.getHighlightFields();
        HighlightField HighlightField = highlightFields.get("title");
        Text[] fragments = HighlightField.fragments();
        //highlight title替换 替换goods中的title
        goods.setTitle(fragments[0].toString());
        goodsList.add(goods);
    }

    for (Goods goods : goodsList) {
        System.out.println(goods);
    }

10、给索引起别名

例如:给 student_index_v2 起别名 student_index_v11 

POST student_index_v2/_alias/student_index_v11

你可能感兴趣的:(ElasticSearch,elasticsearch)