Elasticsearch教程---High Level REST Client创建索引(六)

本文详细介绍了Elasticsearch中索引API的使用方法,包括如何设置分片数量、副本数量,以及如何生成索引mapping。以短信下发表为例,展示了如何定义各种字段类型,如日期、字符串、整数等,并解释了各字段的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第八章 索引api

8.1 代码示例

设置分片API:

private void buildSetting(CreateIndexRequest request) {
    request.settings(Settings.builder().put("index.number_of_shards", 3)
            .put("index.number_of_replicas", 2));
}

生成索引mapping(以短信下发表为例):

/**
 * 生成短信下发表索引结构
 *
 * createDate 创建时间
 * sendDate 发送时间
 * longCode 发送的长号码
 * mobile 下发手机号
 * corpName 发送公司名称
 * smsContent 下发短信内容
 * state 短信下发状态  0 成功 1 失败
 * operatorId  '运营商编号  1 移动 2 联通 3 电信
 * province 省份
 * ipAddr 下发服务器IP地址
 * replyTotal 短信状态报告返回时长(秒)
 * fee 费用
 * @param request 
 * @param type
 * @throws IOException
 */
private void  buildIndexMapping(CreateIndexRequest request, String type) throws IOException {
    XContentBuilder mappingBuilder = JsonXContent.contentBuilder()
            .startObject()
                .startObject("properties")
                    .startObject("mobile")
                    .field("type", "keyword")
                    .field("index", "true")
                    .endObject()

                    .startObject("createDate")
                    .field("type", "date")
                    .field("index", "true")
                    .endObject()

                    .startObject("sendDate")
                    .field("type", "date")
                    .field("index", "true")
                    .endObject()

                    .startObject("longCode")
                    .field("type", "keyword")
                    .field("index", "true")
                    .endObject()

                    .startObject("corpName")
                    .field("type", "keyword")
                    .field("index", "true")
                    .endObject()

                    .startObject("smsContent")
                    .field("type", "text")
                    .field("index", "true")
                    .field("analyzer", "ik_max_word") 
                    .endObject()

                    .startObject("state")
                    .field("type", "integer")
                    .field("index", "true")
                    .endObject()

                    .startObject("province")
                    .field("type", "keyword")
                    .field("index", "true")
                    .endObject()

                    .startObject("operatorId")
                    .field("type", "integer")
                    .field("index", "true")
                    .endObject()

                    .startObject("ipAddr")
                    .field("type", "ip")
                    .field("index", "true")
                    .endObject()

                    .startObject("replyTotal")
                    .field("type", "integer")
                    .field("index", "true")
                    .endObject()

                    .startObject("fee")
                    .field("type", "integer")
                    .field("index", "true")
                    .endObject()
                 .endObject()
            .endObject();
    request.mapping(type, mappingBuilder);
}
package com.javablog.elasticsearch.document.impl;

import com.javablog.elasticsearch.document.IndexService;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service("indexService")
public class IndexServiceImpl implements IndexService {
    private final static Logger log = LoggerFactory.getLogger(IndexServiceImpl.class);
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     *  创建索引
     * @param index       索引名称
     * @param type        索引类型
     * @param request     创建索引的REQUEST
     * @throws IOException
     */
    @Override
    public void createIndex(String index,String type,CreateIndexRequest request) throws IOException {
        log.info("source:" + request.toString());
        if (!existsIndex(index)) {
            CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(response.toString());
            log.info("索引创建结查:" + response.isAcknowledged());
        } else {
            log.warn("索引:{},已经存在,不能再创建。", index);
        }
    }

    /**
     * 删除索引
     * @param index 索引名称
     * @throws IOException
     */
    @Override
    public void deleteIndex(String index) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest();
        getIndexRequest.indices(index);
        if (restHighLevelClient.indices().exists(getIndexRequest)) {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
            log.info("source:" + deleteIndexRequest.toString());
            restHighLevelClient.indices().delete(deleteIndexRequest);
        }
    }

    /**
     * 判断索引是否存在
     * @param index
     * @return
     * @throws IOException
     */
    public boolean existsIndex(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices(index);
        log.info("source:" + request.toString());
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        log.debug("existsIndex: " + exists);
        return exists;
    }

}

完整代码:https://github.com/chutianmen/elasticsearch-examples

### Java Elasticsearch Rest High Level Client 使用教程 #### 创建 Maven 项目并配置依赖项 为了使用 ElasticsearchHigh-Level REST Client,在项目的 `pom.xml` 文件中添加如下依赖: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.9.1</version> </dependency> ``` 此依赖允许应用程序连接到 Elasticsearch 实例并执行各种操作[^2]。 #### 初始化客户端实例 建立与 Elasticsearch 节点之间的连接,通常需要创建一个 `RestHighLevelClient` 对象。下面是一段用于初始化该对象的代码片段: ```java import org.elasticsearch.client.RestHighLevelClient; import org.apache.http.HttpHost; public class EsClient { private static final String ES_HOST = "localhost"; private static final int ES_PORT = 9200; public static RestHighLevelClient createClient() { return new RestHighLevelClient( RestClient.builder(new HttpHost(ES_HOST, ES_PORT, "http")) ); } } ``` 这段代码定义了一个静态方法来构建一个新的 `RestHighLevelClient` 客户端实例,并指定了目标主机地址和端口号[^1]. #### 创建索引并向其中插入数据 一旦成功建立了客户端链接,则可以通过调用相应 API 来管理集群中的资源。这里展示了一种方式用来创建名为 “test-index”的新索引并将 JSON 文档写入它内部: ```java try (RestHighLevelClient client = EsClient.createClient()) { // Create index request with settings and mappings. IndexRequest indexRequest = new IndexRequest("test-index"); Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("field", "value"); indexRequest.source(jsonMap); // Execute the indexing operation. IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { throw new RuntimeException(e); } ``` 上述例子说明了如何向指定名称的新建或已存在的索引里增加一条记录;同时提供了基本字段映射关系以及设置参数. #### 查询现有文档 检索存储于特定索引下的某条或多条匹配条件的数据也是常见的需求之一。以下是实现全文搜索功能的一个简单案例: ```java SearchRequest searchRequest = new SearchRequest("test-index"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchAllQuery()); searchRequest.source(sourceBuilder); // Perform a search on an open index using the created query. try (RestHighLevelClient client = EsClient.createClient()){ SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); System.out.println(searchResponse.getHits().getTotalHits().value); } ``` 此处展示了怎样构造查询请求并通过 `match_all` 类型获取所有符合条件的结果集[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值