← 返回首页
🔍

Elasticsearch集群管理

📂 java ⏱ 1 min 186 words

Elasticsearch集群管理

概述

Elasticsearch集群是Elasticsearch的分布式部署方案。本教程介绍Elasticsearch集群的搭建和管理。

1. 集群配置

# elasticsearch.yml
cluster.name: my-cluster
node.name: node-1
network.host: 0.0.0.0
http.port: 9200
transport.port: 9300
discovery.seed_hosts: ["node-1:9300", "node-2:9300", "node-3:9300"]
cluster.initial_master_nodes: ["node-1", "node-2", "node-3"]

2. Java客户端

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.apache.http.HttpHost;

@Configuration
public class ElasticsearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
            RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
            )
        );
    }
}

3. 实际应用示例

索引管理

@Service
public class IndexManagementService {
    private final RestHighLevelClient client;
    
    public void createIndex(String indexName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.settings(Settings.builder()
            .put("index.number_of_shards", 3)
            .put("index.number_of_replicas", 2));
        
        client.indices().create(request, RequestOptions.DEFAULT);
    }
    
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        client.indices().delete(request, RequestOptions.DEFAULT);
    }
    
    public void reindex(String sourceIndex, String destIndex) throws IOException {
        ReindexRequest request = new ReindexRequest()
            .setSourceIndices(sourceIndex)
            .setDestIndex(destIndex);
        
        client.reindex(request, RequestOptions.DEFAULT);
    }
}

搜索优化

@Service
public class SearchOptimizationService {
    private final RestHighLevelClient client;
    
    public SearchResponse search(String index, String query) throws IOException {
        SearchRequest request = new SearchRequest(index);
        request.source(new SearchSourceBuilder()
            .query(QueryBuilders.multiMatchQuery(query, "title", "content")
                .fuzziness(Fuzziness.AUTO))
            .highlighter(new HighlightBuilder()
                .field("title")
                .field("content"))
            .size(10));
        
        return client.search(request, RequestOptions.DEFAULT);
    }
}

4. 最佳实践

  1. 合理设置分片数量:根据数据量设置分片
  2. 副本配置:设置合适的副本数量
  3. 索引生命周期:管理索引的创建和删除
  4. 性能优化:优化查询和索引性能
  5. 监控集群状态:监控集群健康状态

总结

Elasticsearch集群是Elasticsearch的分布式部署方案。掌握Elasticsearch集群的搭建和管理,可以构建高性能的搜索系统。