专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java 集成 Elasticsearch(Java 集成ureport 导出Word)

temp10 2025-07-08 22:49:00 java教程 1 ℃ 0 评论

一、环境准备与依赖管理

1.1 Elasticsearch 部署方案对比

方案

优点

Java 集成 Elasticsearch(Java 集成ureport 导出Word)

缺点

适用场景

Docker 单节点

快速启动、环境隔离

单点故障风险

开发测试环境

Kubernetes 集群

高可用、弹性伸缩

配置复杂

生产环境

云托管服务

免运维、自动备份

成本较高

云原生应用

推荐使用 Docker 快速启动


docker run -d --name es-node \
  -p 9200:9200 -p 9300:9300 \
  -e "discovery.type=single-node" \
  -e "ES_JAVA_OPTS=-Xms2g -Xmx2g" \
  elasticsearch:8.10.0


1.2 Maven 依赖管理

根据 Elasticsearch 版本选择客户端(版本需严格对应):


<!-- Elasticsearch 8.x 官方客户端 -->
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.10.0</version>
</dependency>

<!-- JSON 处理 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>



二、客户端配置与连接管理

2.1 安全连接配置(关键!)

生产环境必须启用安全认证

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContexts;

public class EsClientFactory {
    public static ElasticsearchClient createSecureClient() throws Exception {
        // 1. SSL 配置(测试环境可忽略证书验证)
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial((chain, authType) -> true)
            .build();

        // 2. 认证信息
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials("elastic", "YourSecurePassword")
        );

        // 3. 创建 REST 客户端
        RestClient restClient = RestClient.builder(new HttpHost("es-host", 9200, "https"))
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                .setSSLContext(sslContext)
                .setDefaultCredentialsProvider(credentialsProvider)
                .setMaxConnTotal(200)  // 连接池配置
                .setMaxConnPerRoute(50)
            );

        // 4. 创建传输层和客户端
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}


2.2 连接池优化建议

最大连接数 :根据并发量设置(建议 100-500)

超时配置


.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
    .setConnectTimeout(5000)  // 5秒连接超时
    .setSocketTimeout(60000)  // 60秒请求超时
)



三、核心数据操作指南

3.1 索引管理(CRUD 操作)


// 创建索引(带映射)
CreateIndexRequest request = new CreateIndexRequest("products");
request.mappings(m -> m
    .properties(p -> p
        .text(t -> t.name("name").fields(f -> f.keyword(k -> k.name("keyword"))))
        .double_(d -> d.name("price"))
        .keyword(k -> k.name("category"))
    )
);
client.indices().create(request, RequestOptions.DEFAULT);


3.2 文档操作


// 插入文档(批量操作更高效)
Product product = new Product(1L, "Wireless Mouse", 29.99, "Electronics");
IndexResponse response = client.index(i -> i
    .index("products")
    .id(product.getId().toString())
    .document(product)
);
System.out.println("文档ID: " + response.id());



四、高级查询技术详解

4.1 复合查询示例


SearchResponse<Product> search = client.search(s -> s
    .index("products")
    .query(q -> q
        .bool(b -> b
            .must(m -> m.match(t -> t.field("name").query("wireless")))
            .filter(f -> f.range(r -> r.field("price").gte(20).lte(100)))
        )
    )
    .from(0)
    .size(10)
    .sort(sort -> sort.field(f -> f.term(t -> t.field("price").order(SortOrder.DESC))))
);


4.2 聚合分析


AggregationContainer aggregation = Aggregation.of(a -> a
    .terms(t -> t.name("category_stats").field("category.keyword"))
    .aggregations(subAgg -> subAgg
        .avg(avg -> avg.name("avg_price").field("price"))
    )
);

SearchResponse<Product> response = client.search(s -> s
    .index("products")
    .aggregation(aggregation)
);



五、企业级应用最佳实践

5.1 性能优化策略

1. 批量操作 :使用 BulkProcessor 进行批量索引

2. 路由优化 :根据业务字段设置路由值

3. 缓存机制 :合理使用过滤器缓存(Filter Cache)

5.2 监控与告警

关键指标 :JVM 内存使用率

索引刷新频率

查询响应时间(P99)

监控工具 :Elasticsearch 监控 API + Prometheus

5.3 安全加固方案

1. 禁用不必要的 API 端点

2. 启用 TLS 1.2+ 加密

3. 定期更新安全补丁


六、Spring Boot 集成方案

6.1 依赖配置


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>


6.2 实体类映射


@Document(indexName = "products")
public class ProductDocument {
    @Id
    private String id;
    
    @Field(type = FieldType.Text, fielddata = true)
    private String name;
    
    @Field(type = FieldType.Double)
    private Double price;
    
    // Getters/Setters
}


6.3 Repository 使用


public interface ProductRepository extends ElasticsearchRepository<ProductDocument, String> {
    List<ProductDocument> findByNameContaining(String keyword);
}



七、常见问题解决方案

问题现象

可能原因

解决方案

查询结果不准确

映射类型错误

检查字段类型和分词器配置

索引速度慢

刷新间隔设置不当

调整 refresh_interval 参数

内存溢出

JVM 堆内存配置不足

调整 -Xms 和 -Xmx 参数

集群脑裂

网络分区未正确处理

配置 discovery.seed_hosts

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表