java 操作es 的基本操作

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

pom的坐标

        <!--es相关-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.10.2</version> <!-- 请根据需要选择合适的版本 -->
        </dependency>

package es;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class EsConnectionExample {

    public static void main(String[] args) throws IOException {
        // 创建客户端
        // 连接es的地址
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("ip", 9200, "http"))); // 修改为你的ES地址和端口

        //创建索引
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("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 = new HashMap<>();
        data.put("name", "huangi"); // 设置文档标题
        data.put("age", "18"); // 设置文档内容
        IndexRequest indexRequest = new IndexRequest("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 = new SearchRequest("my_index"); // "posts" 是 index 的名字
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 查询所有文档
        //searchSourceBuilder.sort("created_at", SortOrder.DESC); // 按 created_at 字段降序排序
        searchSourceBuilder.highlighter(new HighlightBuilder().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 = new SearchRequest("my_index"); // 将"your_index"替换为您要查询的索引名称
        SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder();
        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 = new IndicesAliasesRequest();
        IndicesAliasesRequest.AliasActions aliasAction = new IndicesAliasesRequest.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 = new BufferedReader(new FileReader("user.json"))) {
            String line;

            // 构造 BulkRequest 对象并添加要导入的文档
            BulkRequest request1 = new BulkRequest();
            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 = new IndexRequest("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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值