ElasticSearch 6.x 学习笔记:25.Java API之索引管理

25.1 判定索引是否存在

package cn.hadron;

import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ExistsDemo {

    public static void main(String[] args) throws UnknownHostException {
        //1.设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2.创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("node1"), 9300));
        //3.获取IndicesAdminClient对象
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        //4.判定索引是否存在
        IndicesExistsResponse response=indicesAdminClient.prepareExists("index1").get();
        System.out.println(response.isExists());

    }
}

执行结果

no modules loaded
loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
loaded plugin [org.elasticsearch.transport.Netty4Plugin]
false

Process finished with exit code 0

这里写图片描述

25.2 创建索引

package cn.hadron;

import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class CreateDemo {

    public static void main(String[] args) throws UnknownHostException {
        //1.设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2.创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("node1"), 9300));
        //3.获取IndicesAdminClient对象
        IndicesAdminClient indicesAdminClient = client.admin().indices();
        //4.创建索引
        CreateIndexResponse ciReponse=indicesAdminClient.prepareCreate("index1").get();
        System.out.println(ciReponse.isAcknowledged());

    }
}

执行结果

no modules loaded
loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
loaded plugin [org.elasticsearch.transport.Netty4Plugin]
true

Process finished with exit code 0

这里写图片描述

25.3 封装工具类

ElasticSearch工具类

package cn.hadron.es;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ESUtil {
    //集群名,默认值elasticsearch
    private static final String CLUSTER_NAME = "elasticsearch";
    //ES集群中某个节点
    private static final String HOSTNAME = "node1";
    //连接端口号
    private static final int TCP_PORT = 9300;
    //构建Settings对象
    private static Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).build();
    //TransportClient对象,用于连接ES集群
    private static volatile TransportClient client;

    /**
     * 同步synchronized(*.class)代码块的作用和synchronized static方法作用一样,
     * 对当前对应的*.class进行持锁,static方法和.class一样都是锁的该类本身,同一个监听器
     * @return
     * @throws UnknownHostException
     */
    public static TransportClient getClient(){
        if(client==null){
            synchronized (TransportClient.class){
                try {
                    client=new PreBuiltTransportClient(settings)
                        .addTransportAddress(new TransportAddress(InetAddress.getByName(HOSTNAME), TCP_PORT));
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        return client;
    }

    /**
     * 获取索引管理的IndicesAdminClient
     */
    public static IndicesAdminClient getAdminClient() {
        return getClient().admin().indices();
    }

    /**
     * 判定索引是否存在
     * @param indexName
     * @return
     */
    public static boolean isExists(String indexName){
        IndicesExistsResponse response=getAdminClient().prepareExists(indexName).get();
        return response.isExists()?true:false;
    }
    /**
     * 创建索引
     * @param indexName
     * @return
     */
    public static boolean createIndex(String indexName){
        CreateIndexResponse createIndexResponse = getAdminClient()
                .prepareCreate(indexName.toLowerCase())
                .get();
        return createIndexResponse.isAcknowledged()?true:false;
    }

    /**
     * 创建索引
     * @param indexName 索引名
     * @param shards   分片数
     * @param replicas  副本数
     * @return
     */
    public static boolean createIndex(String indexName, int shards, int replicas) {
        Settings settings = Settings.builder()
                .put("index.number_of_shards", shards)
                .put("index.number_of_replicas", replicas)
                .build();
        CreateIndexResponse createIndexResponse = getAdminClient()
                .prepareCreate(indexName.toLowerCase())
                .setSettings(settings)
                .execute().actionGet();
        return createIndexResponse.isAcknowledged()?true:false;
    }

    /**
     * 位索引indexName设置mapping
     * @param indexName
     * @param typeName
     * @param mapping
     */
    public static void setMapping(String indexName, String typeName, String mapping) {
        getAdminClient().preparePutMapping(indexName)
                .setType(typeName)
                .setSource(mapping, XContentType.JSON)
                .get();
    }

    /**
     * 删除索引
     * @param indexName
     * @return
     */
    public static boolean deleteIndex(String indexName) {
        DeleteIndexResponse deleteResponse = getAdminClient()
                .prepareDelete(indexName.toLowerCase())
                .execute()
                .actionGet();
        return deleteResponse.isAcknowledged()?true:false;
    }
}

测试程序

package cn.hadron;
import cn.hadron.es.*;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public class ESUtilDemo {
    public static void main(String[] args) {
        //1.判定索引是否存在
        boolean flag=ESUtil.isExists("index1");
        System.out.println("isExists:"+flag);
        //2.创建索引
        flag=ESUtil.createIndex("index1", 3, 0);
        System.out.println("createIndex:"+flag);
        //3.设置Mapping
        try {
            XContentBuilder builder = jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("id")
                    .field("type", "long")
                    .endObject()
                    .startObject("title")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .field("search_analyzer", "ik_max_word")
                    .field("boost", 2)
                    .endObject()
                    .startObject("content")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .field("search_analyzer", "ik_max_word")
                    .endObject()
                    .startObject("postdate")
                    .field("type", "date")
                    .field("format", "yyyy-MM-dd HH:mm:ss")
                    .endObject()
                    .startObject("url")
                    .field("type", "keyword")
                    .endObject()
                    .endObject()
                    .endObject();
            System.out.println(builder.string());
            ESUtil.setMapping("index1", "blog", builder.string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

执行结果

no modules loaded
loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
loaded plugin [org.elasticsearch.transport.Netty4Plugin]
isExists:false
createIndex:true
{"properties":{"id":{"type":"long"},"title":{"type":"text","analyzer":"ik_max_word","search_analyzer":"ik_max_word","boost":2},"content":{"type":"text","analyzer":"ik_max_word","search_analyzer":"ik_max_word"},"postdate":{"type":"date","format":"yyyy-MM-dd HH:mm:ss"},"url":{"type":"keyword"}}}

Process finished with exit code 0

这里写图片描述

通过Kibana查询

GET index1/_mapping
{
  "index1": {
    "mappings": {
      "blog": {
        "properties": {
          "content": { "type": "text", "analyzer": "ik_max_word" },
          "id": { "type": "long" },
          "postdate": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss" },
          "title": { "type": "text", "boost": 2, "analyzer": "ik_max_word" },
          "url": { "type": "keyword" } }
      }
    }
  }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要对百万数据的 Elasticsearch 索引进行重命名,可以尝试以下性能优化方法: 1. 执行重命名操作时,尽量避免在同一节点上同时执行其他繁重的操作,以减少节点的负载和竞争。 2. 可以考虑将索引分成多个分片,然后在多个节点上执行并行的重命名操作。这可以通过设置索引的分片数来实现,例如: ``` PUT /my_index/_settings { "index": { "number_of_shards": 5 } } ``` 这将将索引分成 5 个分片,每个分片都可以在不同的节点上处理。 3. 使用 Elasticsearch Bulk API 执行批量操作。Bulk API 可以一次性处理多个操作,从而提高索引重命名的性能,例如: ``` POST /_bulk { "update": { "_id": "1", "_index": "my_index", "_type": "_doc" } } { "doc": { "name": "new_name" } } { "update": { "_id": "2", "_index": "my_index", "_type": "_doc" } } { "doc": { "name": "new_name" } } ... ``` 这将在一次 API 调用中更新多个文档的名称,而不是逐个更新。 4. 在执行重命名操作之前,可以考虑关闭索引的刷新机制。刷新操作会将新数据写入磁盘,从而增加索引重命名的时间和开销。可以使用以下命令关闭索引的刷新机制: ``` POST /my_index/_settings { "index": { "refresh_interval": "-1" } } ``` 这将关闭索引的刷新机制。在执行完索引重命名操作后,可以使用以下命令重新启用刷新机制: ``` POST /my_index/_settings { "index": { "refresh_interval": "1s" } } ``` 这将每秒钟执行一次索引刷新操作。请注意,关闭刷新机制可能会导致某些查询结果不准确,因为查询可能会返回尚未刷新的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值