首页 > 其他分享 >ES常用命令

ES常用命令

时间:2023-05-21 13:03:11浏览次数:50  
标签:index name DEFAULT searchRequest client 常用命令 new ES

一、Maven依赖

在使用Java连接Elasticsearch前,需要在Maven中引入相关的依赖包。在pom.xml文件中添加以下依赖:

<!--elasticsearch客户端-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.14.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.14.0</version>
</dependency>

二、Elasticsearch的连接

在Java中连接Elasticsearch需要使用Elasticsearch的客户端进行连接。可以使用RestHighLevelClient作为HttpClient的包装类,来连接Elasticsearch。在代码中,可以使用以下方法进行连接:

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

请注意,代码中的“localhost”为Elasticsearch服务器的地址,“9200”为Elasticsearch服务器的端口号,“http”表示使用的通讯协议为HTTP。

三、Index的增删查改

在Elasticsearch中,索引是一类具有共同属性的文档集合。在Java中可以使用以下方法进行索引的增删查改操作:

1. 创建索引

CreateIndexRequest request = new CreateIndexRequest("your_index_name");
client.indices().create(request, RequestOptions.DEFAULT);

2. 删除索引

DeleteIndexRequest deleteRequest = new DeleteIndexRequest("your_index_name");
client.indices().delete(deleteRequest, RequestOptions.DEFAULT);

3. 判断索引是否存在

IndicesExistsRequest existsRequest = new IndicesExistsRequest("your_index_name");
boolean exists = client.indices().exists(existsRequest, RequestOptions.DEFAULT);

4. 索引配置更新

PutSettingsRequest settingsRequest = new PutSettingsRequest().settings(Settings.builder().put("index.number_of_replicas", 2));
client.indices().putSettings(settingsRequest, RequestOptions.DEFAULT);

5. 索引别名设置

Aliases aliases = new Aliases.Builder().addAlias("alias_name", "index_name").build();
IndicesAliasesRequest aliasesRequest = new IndicesAliasesRequest().addAliasAction(aliases);
client.indices().updateAliases(aliasesRequest, RequestOptions.DEFAULT);

四、 数据的增删查改

在Elasticsearch中,每条记录都称为一个文档。可以使用以下代码进行数据的增删查改等操作:

1. 新增或更新数据

IndexRequest request = new IndexRequest("your_index_name").id("1").source("field_name", "field_value");
client.index(request, RequestOptions.DEFAULT);

2. 删除数据

DeleteRequest deleteRequest = new DeleteRequest("your_index_name").id("1");
client.delete(deleteRequest, RequestOptions.DEFAULT);

3. 判断数据是否存在

GetRequest existsRequest = new GetRequest("your_index_name").id("1");
boolean exists = client.exists(existsRequest, RequestOptions.DEFAULT);

4. 获取数据

GetRequest getRequest = new GetRequest("your_index_name").id("1");
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
String index = response.getIndex();
String id = response.getId();
if (response.isExists()) {
    String sourceAsString = response.getSourceAsString();
}

5. 更新数据

UpdateRequest updateRequest = new UpdateRequest("your_index_name", "1").doc("field_name", "field_value");
client.update(updateRequest, RequestOptions.DEFAULT);

五、 数据的批量操作

在实际的应用场景中,可能会需要进行数据的批量操作。以下是几个常用的批量操作方法:

1. 批量新增'

BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest("your_index_name").id("1").source("field_name", "field_value"));
bulkRequest.add(new IndexRequest("your_index_name").id("2").source("field_name", "field_value2"));
client.bulk(bulkRequest, RequestOptions.DEFAULT);

2. 全部查询

SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

3. 条件查询

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.termQuery("field_name", "field_value");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

4. 分页查询

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(0);
sourceBuilder.size(20);
sourceBuilder.query(QueryBuilders.matchAllQuery());
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

5. 范围查询

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.rangeQuery("date_field").gte("2021-01-01").lte("2021-01-31");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

6. 最大值查询

SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.max("agg_max").field("field_name");
sourceBuilder.aggregation(aggregationBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

7. 模糊查询

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("field_name", "*test*");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("your_index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

8.聚合查询

假设有一个包含学生信息的ES索引,每个文档包含了学生的姓名(name)、性别(gender)、年龄(age)和成绩(score)等属性。现在需要对学生数据进行一些聚合统计操作,例如按性别分组计算平均年龄和平均成绩以及每个年龄段中的最高成绩。

//创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(new HttpHost("localhost", 9200, "http")));

//按性别分组计算平均年龄和平均成绩
SearchRequest searchRequest = new SearchRequest("students");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size(0);
searchSourceBuilder.aggregation(
    AggregationBuilders.terms("gender_terms").field("gender")
    .subAggregation(AggregationBuilders.avg("age_avg").field("age"))
    .subAggregation(AggregationBuilders.avg("score_avg").field("score"))
);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Terms genderTerms = searchResponse.getAggregations().get("gender_terms");
List<? extends Terms.Bucket> buckets = genderTerms.getBuckets();
for (Terms.Bucket bucket : buckets) {
    String gender = bucket.getKeyAsString();
    Avg ageAvg = bucket.getAggregations().get("age_avg");
    double avgAge = ageAvg.getValue();
    Avg scoreAvg = bucket.getAggregations().get("score_avg");
    double avgScore = scoreAvg.getValue();
    System.out.println("Gender: " + gender + ", Avg Age: " + avgAge + ", Avg Score: " + avgScore);
}

//每个年龄段中计算最高成绩
searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size(0);
searchSourceBuilder.aggregation(
    AggregationBuilders.range("age_range").field("age")
    .addUnboundedTo(18)
    .addRange(18, 20)
    .addRange(20, 22)
    .addUnboundedFrom(22)
    .subAggregation(AggregationBuilders.max("score_max").field("score"))
);
searchRequest.source(searchSourceBuilder);
searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Range ageRange = searchResponse.getAggregations().get("age_range");
for (Range.Bucket bucket : ageRange.getBuckets()) {
    String age = bucket.getKeyAsString();
    Max scoreMax = bucket.getAggregations().get("score_max");
    double maxScore = scoreMax.getValue();
    System.out.println("Age: " + age + ", Max Score: " + maxScore);
}

代码中按性别分组计算平均年龄和平均成绩,然后再对每个年龄段中计算最高成绩。聚合查询操作使用“AggregationBuilders”类中的方法来构建聚合查询条件。

9.组合查询

假设有一个包含商品信息的ES索引,每个文档包含了商品的名称(name)、价格(price)、品牌(brand)和类别(category)等属性。现在需要根据用户的查询条件进行组合查询,例如查询价格在一定范围内、品牌为“Samsung”并且类别为“手机”的商品,同时按价格从低到高进行排序。

//创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(new HttpHost("localhost", 9200, "http")));

//组合查询条件
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(
    QueryBuilders.boolQuery()
    .must(QueryBuilders.rangeQuery("price").gte(1000).lte(2000))
    .must(QueryBuilders.termQuery("brand", "Samsung"))
    .must(QueryBuilders.termQuery("category", "手机"))
);
searchSourceBuilder.sort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
searchRequest.source(searchSourceBuilder);

//执行查询操作
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
    String name = hit.getSourceAsMap().get("name").toString();
    String price = hit.getSourceAsMap().get("price").toString();
    String brand = hit.getSourceAsMap().get("brand").toString();
    String category = hit.getSourceAsMap().get("category").toString();
    System.out.println("Product name: " + name + ", Price: " + price + ", Brand: " + brand + ", Category: " + category);
}

代码中使用“QueryBuilders”类中的方法来构建查询条件,查询条件包括价格在一定范围内、品牌为“Samsung”并且类别为“手机”。还使用了“SortBuilders”类中的方法来构建排序条件,按价格从低到高进行排序。

标签:index,name,DEFAULT,searchRequest,client,常用命令,new,ES
From: https://blog.51cto.com/learningfish/6318994

相关文章

  • C++ 测试框架 GoogleTest 初学者入门篇 甲
    *以下内容为本人的学习笔记,如需要转载,请声明原文链接微信公众号「ENG八戒」https://mp.weixin.qq.com/s/BS_u9A4EY50y4vDDuxkCAQ开发者虽然主要负责工程里的开发任务,但是每个开发完毕的功能都是需要开发者自测通过的,所以经常会听到开发者提起单元测试的话题。那么今天我就带大伙......
  • python基础-进程池、submit同异步调用、shutdown参数、ProcessPoolExecutor进程池、进
    转载:(14条消息)python基础-进程池、submit同异步调用、shutdown参数、ProcessPoolExecutor进程池、进程池ftp_pythonsubmit_易辰_的博客-CSDN博客引入进程池在学习线程池之前,我们先看一个例子frommultiprocessingimportProcessimporttimedeftask(name):print(......
  • k8s 1.24.14 Ingress-nginx 的部署
    前言:本次部署使用了高可用的形式,会在每个node节点做亲和性(master不部署),让每一个pod都部署上去,然后加入NGINX去过负载,这样我们之间用NGINX的80端口访问域名就可以了。MountVolume.SetUpfailedforvolume"webhook-cert":secret"ingress-nginx-admission"notfound。......
  • 计算机图形学入门——GAMES101第一课笔记
    一、光栅化将三维空间的几何形体显示在屏幕上,就是光栅化(Rasterization)。 虎书中有这么一段话: Theprocessoffindingallthepixelsinanimagethatareoccupiedbyageometricprimitiveiscalledrasterization;即光栅化就是找到所有被几何原型所占据的所有像素点......
  • AtCoder Regular Contest 130 E Increasing Minimum
    这题太神仙了吧!感觉还不是很懂,但是尽力理一下思路。设\(t_x\)为最大的\(j\)使得\(i_j=x\),不存在则\(t_x=0\)。设\(1\simn\)的数按照\(t\)从小到大排序后是\(p_1,p_2,...,p_n\),设\(q_i\)为\(i\)在\(p\)中的排名,即\(q_{p_i}=i\)。发现正着不好考虑,......
  • python进程池ProcessPoolExecutor的用法与实现分析
    转载:(14条消息)【Python随笔】python进程池ProcessPoolExecutor的用法与实现分析_utmhikari的博客-CSDN博客concurrent.futures—Launchingparalleltasks—Python3.11.3documentation在python开发期间,由于GIL的原因,不能直接采用并行的方式处理代码逻辑。在multiprocess......
  • [nodejs]国内npm安装nodejs modules失败的几个解决方案
    使用npm安装node模块时经常有卡住安装失败的情况,如图所示。原因在于npm服务器在美国,还有就是某强大的防火墙作用。这样的问题导致很多新手放弃使用node,几乎每天都有新手再问这个问题。现在分享一下解决这个问题的解决方案1.可以通过一劳永逸的方式修改代理地址2.更换npm源拼rp (......
  • 前端项目实战79-postgrest的增删改查简单文档
    Postgrest使用手册1过滤出is_delete=0的数据分页查询并按照id倒叙排列2GEThttp://127.0.0.1:3000/t_wms_location?is_delete=eq.0&limit=10&offset=23&order=id.desc仓库管理postgrest返回总页数:1......
  • 袋鼠云数栈UI5.0焕新升级,全新设计语言DT Design,更懂视觉更懂你!
    数栈作为袋鼠云打造的一站式数据开发与治理平台,从2016年发布第⼀个版本开始,就始终坚持着以技术为核⼼、安全为底线、提效为⽬标、中台为战略的思想,坚定不移地⾛国产化信创路线,不断推进产品功能迭代、技术创新、服务细化和性能升级。伴随业务的⻜速发展,数栈设计团队也启动了针对数栈......
  • Codeforces Round 874 (Div. 3) A-G
    比赛地址A.MusicalPuzzle题意:给出一个字符串,求有多少个不同的长度为2的子串Solution直接set存即可voidsolve(){ intn;cin>>n; strings;cin>>s; set<string>st; for(inti=0;i<n-1;i++) { st.insert(s.substr(i,2)); } cout<<st.size()<<"\n"......