0


java 操作es 的基本操作

  • 创建索引
  • 创建索引别名
  • 索引的相关设置
  • 查询索引数据
  • bulk 导入数据
  • 持续更新中~

pom的坐标

<!--es相关--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.10.2</version><!-- 请根据需要选择合适的版本 --></dependency>
packagees;importcom.alibaba.fastjson.JSONObject;importorg.apache.http.HttpHost;importorg.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;importorg.elasticsearch.action.admin.indices.create.CreateIndexRequest;importorg.elasticsearch.action.admin.indices.create.CreateIndexResponse;importorg.elasticsearch.action.bulk.BulkRequest;importorg.elasticsearch.action.bulk.BulkResponse;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.action.search.SearchRequest;importorg.elasticsearch.action.search.SearchResponse;importorg.elasticsearch.action.support.master.AcknowledgedResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.common.settings.Settings;importorg.elasticsearch.common.xcontent.XContentBuilder;importorg.elasticsearch.common.xcontent.XContentFactory;importorg.elasticsearch.common.xcontent.XContentType;importorg.elasticsearch.index.query.QueryBuilders;importorg.elasticsearch.search.SearchHit;importorg.elasticsearch.search.builder.SearchSourceBuilder;importorg.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;importorg.elasticsearch.search.fetch.subphase.highlight.HighlightField;importorg.elasticsearch.search.sort.SortOrder;importjava.io.BufferedReader;importjava.io.FileReader;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;publicclassEsConnectionExample{publicstaticvoidmain(String[] args)throwsIOException{// 创建客户端// 连接es的地址RestHighLevelClient client =newRestHighLevelClient(RestClient.builder(newHttpHost("ip",9200,"http")));// 修改为你的ES地址和端口//创建索引CreateIndexRequest createIndexRequest =newCreateIndexRequest("my_index");// 创建名为"my_index"的索引
        createIndexRequest.settings(Settings.builder().put("index.number_of_shards",3)// 设置分片数.put("index.number_of_replicas",2)// 设置副本数);CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest,RequestOptions.DEFAULT);System.out.println("索引创建成功:"+ createIndexResponse.isAcknowledged());//给索引插入数据Map<String,Object> data =newHashMap<>();
        data.put("name","huangi");// 设置文档标题
        data.put("age","18");// 设置文档内容IndexRequest indexRequest =newIndexRequest("my_index");// 将数据插入到"my_index"索引中
        indexRequest.id("1");// 设置文档ID为1
        indexRequest.source(data,XContentType.JSON);// 将数据转换为JSON格式并设置到索引请求中IndexResponse indexResponse = client.index(indexRequest,RequestOptions.DEFAULT);System.out.println("数据插入成功:"+ indexResponse.getResult().name().toLowerCase());//---------------------------------------------------------------------                             //查询一个名叫my_index的索引下列是age,值为25的数据,不是格式化展示                                                            // 构建查询请求                                                                                          // 创建搜索索引请求SearchRequest searchRequest =newSearchRequest("my_index");// "posts" 是 index 的名字SearchSourceBuilder searchSourceBuilder =newSearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());// 查询所有文档//searchSourceBuilder.sort("created_at", SortOrder.DESC); // 按 created_at 字段降序排序
        searchSourceBuilder.highlighter(newHighlightBuilder().field("content").preTags("<em>").postTags("</em>"));// 对 content 字段进行高亮显示
        searchRequest.source(searchSourceBuilder);// 执行搜索并获取响应SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);System.out.println("Total hits: "+ searchResponse.getHits().getTotalHits().value);Map<String,HighlightField> highlightFields = searchResponse.getHits().getHits()[0].getHighlightFields();for(HighlightField highlightField : highlightFields.values()){System.out.println("输出:"+highlightField.fragments()[0].string());// 输出高亮显示的内容片段}//---------------------------------------------------------------------//查询一个名叫my_index的索引下列是age,值为25的数据,并格式化展示// 构建查询请求SearchRequest searchRequest1 =newSearchRequest("my_index");// 将"your_index"替换为您要查询的索引名称SearchSourceBuilder searchSourceBuilder1 =newSearchSourceBuilder();
        searchSourceBuilder1.query(QueryBuilders.matchQuery("age","25"));// 将"field_name"替换为您要查询的字段名称,将"query_value"替换为您要匹配的查询值
        searchRequest1.source(searchSourceBuilder1);// 执行查询请求并获取响应SearchResponse searchResponse1 = client.search(searchRequest1,RequestOptions.DEFAULT);// 处理响应数据(例如打印结果)System.out.println("Total hits: "+ searchResponse1.getHits().getTotalHits().value);System.out.println("Hits: "+JSONObject.toJSONString(searchResponse1.getHits().getHits()));// 处理响应数据(例如打印结果)for(SearchHit hit : searchResponse1.getHits()){HighlightField highlightField = hit.getHighlightFields().get("field_name");// 将"field_name"替换为您要高亮的字段名称String highlightedValue = highlightField !=null? highlightField.getFragments()[0].string(): hit.getSourceAsString();// 如果存在高亮结果,则获取第一个片段的值,否则获取原始字段的值System.out.println(highlightedValue);// 打印字段的值}//---------------------------------------------------------------------//创建索引别名// 索引名称和别名String indexName ="my_index";String aliasName ="my_index_alias";// 创建一个别名请求IndicesAliasesRequest request =newIndicesAliasesRequest();IndicesAliasesRequest.AliasActions aliasAction =newIndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD).index(indexName).alias(aliasName);
        request.addAliasAction(aliasAction);// 执行请求AcknowledgedResponse indicesAliasesResponse = client.indices().updateAliases(request,RequestOptions.DEFAULT);// 检查操作是否成功boolean acknowledged = indicesAliasesResponse.isAcknowledged();if(acknowledged){System.out.println("Alias was successfully added to the index.");}else{System.out.println("Alias addition was not acknowledged.");}//---------------------------------------------------------------------//bulk 导入try(BufferedReader reader =newBufferedReader(newFileReader("user.json"))){String line;// 构造 BulkRequest 对象并添加要导入的文档BulkRequest request1 =newBulkRequest();while((line = reader.readLine())!=null){XContentBuilder builder =XContentFactory.jsonBuilder().startObject().field("name", line).field("age", line).field("sex", line).field("telephone", line).endObject();IndexRequest indexRequest1 =newIndexRequest("my_index").source(builder);
                request1.add(indexRequest1);}// 发送 BulkRequest 请求BulkResponse response = client.bulk(request1,RequestOptions.DEFAULT);if(response.hasFailures()){System.out.println("Failed to import documents.");}else{System.out.println("Documents imported successfully!");}}catch(IOException e){
            e.printStackTrace();}finally{// 关闭 ElasticSearch 客户端连接
            client.close();}// 关闭客户端连接
        client.close();}}
标签: java elasticsearch

本文转载自: https://blog.csdn.net/HC_MM/article/details/135697021
版权归原作者 黄妹妹儿 所有, 如有侵权,请联系我们删除。

“java 操作es 的基本操作”的评论:

还没有评论