spring boot 集成 elasticsearch 7.x (一)

spring boot 版本 2.2.1
elasticsearch 版本:7.4

使用 java api 的 high level client

1、Maven 配置 pom.xml

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.4.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.4.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.4.0</version>
</dependency>

注意:这里需要加上 exclusions

applicaton.yml 配置

es:
    host: 127.0.0.1
    port: 9200
    scheme: http

2、创建索引

@Autowired
    RestHighLevelClient restHighLevelClient;
    /**
     * @param idxName 索引名称
     * @param idxSQL  索引描述
     * @return void
     */
    public void createIndex(String idxName, String idxSQL) {
        try {
            if (!this.indexExist(idxName)) {
                log.error(" idxName={} 已经存在,idxSql={}", idxName, idxSQL);
                return;
            }
            CreateIndexRequest request = new CreateIndexRequest(idxName);
            buildSetting(request);
            request.mapping(idxSQL, XContentType.JSON);
            CreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (!res.isAcknowledged()) {
                throw new RuntimeException("初始化失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

 /**
 * 断某个index是否存在
 *
 * @param idxName index名
 * @return boolean
 */
public boolean indexExist(String idxName) throws Exception {
    GetIndexRequest request = new GetIndexRequest(idxName);
    request.local(false);
    request.humanReadable(true);
    request.includeDefaults(false);
    request.indicesOptions(IndicesOptions.lenientExpandOpen());
    return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
}



/**
 * 设置分片
 *
 * @param request
 * @return void
 */
public void buildSetting(CreateIndexRequest request) {
    request.settings(Settings.builder().put("index.number_of_shards", 3)
            .put("index.number_of_replicas", 2));
}


注:图片来自 pixabay.com

你可能感兴趣的:(elasticsearch)