首页 > 编程语言 >Elasticsearch——JavaApi实现索引管理

Elasticsearch——JavaApi实现索引管理

时间:2022-10-14 16:40:36浏览次数:64  
标签:text builder indexRequest acknowledged 索引 Elasticsearch JavaApi new properties

版本

不同版本的elasticsearch-rest-high-level-client和 elasticsearch之间存在兼容风险,请确保和elasticsearch版本一致,否则会出现无法预计的错误。

es配置

maven依赖

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

配置application.properties

spring.application.name=service-search

#多个节点用逗号隔开
elasticsearch.hostlist=127.0.0.1:9200

创建配置类ElasticsearchConfig

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient(){
        String[] split = hostlist.split(",");
        HttpHost[] httpHost = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] item = split[i].split(":");
            httpHost[i] = new HttpHost(item[0],Integer.parseInt(item[1]),"http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHost));
    }
}

索引管理测试代码

同步新增索引

PUT /my_index

{
	"settings":{
		"number_of_shards": "1",
		"number_of_replicas": "1"
	},
	"mappings":{
		"properties":{
			"field1":{
				"type": "text"
			},
			"field2":{
				"type": "text"
			}
		}
	},
	"aliases":{
		"default_index":{}
	}
}
@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
@Slf4j
public class TestIndex {

    @Autowired
    private RestHighLevelClient client;

    //新增索引
    @Test
    public void testCreateIndex() throws IOException {
        /*PUT /my_index
        {
            "settings":{
                "number_of_shards": "1",
                        "number_of_replicas": "1"
            },
                "mappings":{
                "properties":{
                    "field1":{
                        "type": "text"
                    },
                    "field2":{
                        "type": "text"
                    }
                }
            },
                "aliases":{
                "default_index":{}
            }
        }*/

        //1、构建请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("my_index");
        //设置参数
        indexRequest.settings(Settings.builder()
                .put("number_of_shards","1")
                .put("number_of_replicas","1").build());

        //--------------------设置映射的三种方式-------------------------
        //设置映射方式1
        indexRequest.mapping("{" +
                "  \"properties\":{" +
                "    \"field1\":{\"type\": \"text\"}," +
                "    \"field2\":{\"type\": \"text\"}" +
                "  }" +
                "}", XContentType.JSON);

        //设置映射方式2
        Map<String,Object> field1 = new HashMap<>();
        field1.put("type","text");
        field1.put("analyzer","standard");
        Map<String,Object> field2 = new HashMap<>();
        field2.put("type","text");
        Map<String,Object> properties = new HashMap<>();
        properties.put("field1",field1);
        properties.put("field2",field2);
        Map<String,Object> mapping = new HashMap<>();
        mapping.put("properties",properties);
        indexRequest.mapping(mapping);

        //设置映射方式3
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.startObject("properties");
            {
                builder.startObject("field1");
                {
                    builder.field("type","text");
                }
                builder.endObject();
                builder.startObject("field2");
                {
                    builder.field("type","text");
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
        indexRequest.mapping(builder);

        //创建别名
        indexRequest.alias(new Alias("pro_index"));

        //-------------------------可选参数------------------------
        //超时时间
        indexRequest.setTimeout(TimeValue.timeValueSeconds(5));

        //主节点超时时间
        indexRequest.setMasterTimeout(TimeValue.timeValueSeconds(5));

        //设置创建索引API返回相应之前等待活动分片的数量
        indexRequest.waitForActiveShards(ActiveShardCount.ONE);

        //2、执行
        //操作索引的客户端
        IndicesClient indices = client.indices();
        CreateIndexResponse indexResponse = indices.create(indexRequest, RequestOptions.DEFAULT);

        //3、获取结果
        //得到相应
        boolean acknowledged = indexResponse.isAcknowledged();
        //指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本
        boolean shardsAcknowledged = indexResponse.isShardsAcknowledged();
        System.out.println("acknowledged: "+acknowledged);
        System.out.println("shardsAcknowledged: "+shardsAcknowledged);
    }
}

异步新增索引

@Test
public void testCreateIndexAsync() throws IOException {

	//1、构建请求
	CreateIndexRequest indexRequest = new CreateIndexRequest("my_index");
	//设置参数
	indexRequest.settings(Settings.builder()
			.put("number_of_shards","1")
			.put("number_of_replicas","1").build());

	//--------------------设置映射的三种方式-------------------------
	//设置映射方式1
	indexRequest.mapping("{" +
			"  \"properties\":{" +
			"    \"field1\":{\"type\": \"text\"}," +
			"    \"field2\":{\"type\": \"text\"}" +
			"  }" +
			"}", XContentType.JSON);

	//设置映射方式2
	Map<String,Object> field1 = new HashMap<>();
	field1.put("type","text");
	field1.put("analyzer","standard");
	Map<String,Object> field2 = new HashMap<>();
	field2.put("type","text");
	Map<String,Object> properties = new HashMap<>();
	properties.put("field1",field1);
	properties.put("field2",field2);
	Map<String,Object> mapping = new HashMap<>();
	mapping.put("properties",properties);
	indexRequest.mapping(mapping);

	//设置映射方式3
	XContentBuilder builder = XContentFactory.jsonBuilder();
	builder.startObject();
	{
		builder.startObject("properties");
		{
			builder.startObject("field1");
			{
				builder.field("type","text");
			}
			builder.endObject();
			builder.startObject("field2");
			{
				builder.field("type","text");
			}
			builder.endObject();
		}
		builder.endObject();
	}
	builder.endObject();
	indexRequest.mapping(builder);

	//创建别名
	indexRequest.alias(new Alias("pro_index"));

	//-------------------------可选参数------------------------
	//超时时间
	indexRequest.setTimeout(TimeValue.timeValueSeconds(5));

	//主节点超时时间
	indexRequest.setMasterTimeout(TimeValue.timeValueSeconds(5));

	//设置创建索引API返回相应之前等待活动分片的数量
	indexRequest.waitForActiveShards(ActiveShardCount.ONE);

	//2、执行
	ActionListener<CreateIndexResponse> listener = new ActionListener<CreateIndexResponse>() {
		@Override
		public void onResponse(CreateIndexResponse createIndexResponse) {
			//3、获取结果
			//得到相应
			boolean acknowledged = createIndexResponse.isAcknowledged();
			//指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本
			boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
			System.out.println("acknowledged: "+acknowledged);
			System.out.println("shardsAcknowledged: "+shardsAcknowledged);
		}

		@Override
		public void onFailure(Exception e) {
			log.error("error",e);
		}
	};

	client.indices().createAsync(indexRequest, RequestOptions.DEFAULT,listener);

	try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

同步删除索引

@Test
public void testDeleteIndex() throws IOException {
	//创建删除索引请求
	DeleteIndexRequest indexRequest = new DeleteIndexRequest("my_book");
	//执行
	AcknowledgedResponse delete = client.indices().delete(indexRequest, RequestOptions.DEFAULT);
	//获取响应
	boolean acknowledged = delete.isAcknowledged();
	System.out.println("acknowledged: "+acknowledged);
}

异步删除索引

@Test
public void testDeleteIndexAsync() throws IOException {
	//创建删除索引请求
	DeleteIndexRequest indexRequest = new DeleteIndexRequest("my_book");
	ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
		@Override
		public void onResponse(AcknowledgedResponse acknowledgedResponse) {
			//获取响应
			boolean acknowledged = acknowledgedResponse.isAcknowledged();
			System.out.println("acknowledged: "+acknowledged);
		}

		@Override
		public void onFailure(Exception e) {
			log.error("error",e);
		}
	};
	//执行
	client.indices().delete(indexRequest, RequestOptions.DEFAULT);
}

判断索引是否存在

@Test
public void testExistIndex() throws IOException {
	GetIndexRequest request = new GetIndexRequest("my_book");
	//参数
	request.local();//从主节点返回本地索引信息状态
	request.humanReadable(true);//以适合人类的格式返回
	request.includeDefaults(false);//是否返回每个索引的所有默认配置

	boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
	System.out.println("index exists: "+exists);
}

关闭索引

@Test
public void testCloseIndex() throws IOException {
	CloseIndexRequest request = new CloseIndexRequest("my_book");
	AcknowledgedResponse close = client.indices().close(request, RequestOptions.DEFAULT);
	boolean acknowledged = close.isAcknowledged();
	System.out.println("acknowledged: "+acknowledged);
}

开启索引

@Test
public void testOpenIndex() throws IOException {
	OpenIndexRequest request = new OpenIndexRequest("my_book");
	OpenIndexResponse open = client.indices().open(request, RequestOptions.DEFAULT);
	boolean acknowledged = open.isAcknowledged();
	System.out.println("index open: "+acknowledged);
}

标签:text,builder,indexRequest,acknowledged,索引,Elasticsearch,JavaApi,new,properties
From: https://blog.51cto.com/u_14014612/5757427

相关文章

  • Elasticsearch——search搜索入门
    Search的运行机制Search执行的时候分为两个运行步骤:Query阶段Fetch阶段Query阶段Fetch阶段相关性算分问题相关性算分在shard与shard之间是相互独立的,也就意味着......
  • MySQL索引(下)
    MySQL索引(下)该文摘抄自林晓斌老师的文章在上一篇文章中,介绍了InnoDB索引的数据结构模型,今天我们再继续聊聊跟MySQL索引有关的概念在开始这篇文章之前,我们先来看一下......
  • mysql创建索引的语句
     1. altertable table_name addindexindex_name(column) 2.altertabletable_nameaddprimarykey(column)/addunique主键索引或者唯一值索引 3.cre......
  • MySQL索引(上)
    MySQL索引(上)该文摘抄自林晓斌老师的文章索引是一种数据结构,索引的出现其实就是为了提高数据查询的效率,就像书的目录一样。一本500页的书,如果你想快速找到其中的某一个知......
  • 1.0 Mysql索引的数据结构与算法
    索引是高效获取排序好的数据结构索引本身就是数据一部分关键信息,通过索引大大减少索引的数据量。索引信息需要额外的空间存储。创建和维护索引本身也会降低对数据的操作......
  • Python 的切片为什么不会索引越界?
    切片(slice)是Python中一种很有特色的特性,在正式开始之前,我们先来复习一下关于切片的知识吧。切片主要用于序列对象中,按照索引区间截取出一段索引的内容。切片的书写形式:[i......
  • Python爬虫之mongodb的索引操作
    Mongodb的索引操作学习目标掌握mongodb索引的创建,删除操作掌握mongodb查看索引的方法掌握mongodb创建唯一索引的方法1.为什么mongdb需要创建索引加快查询速度进行数据的......
  • 后端程序员必备:索引失效的十大杂症
    背景最近生产爆出一条慢sql,原因是用了or和!=,导致索引失效。于是,总结了索引失效的十大杂症,希望对大家有帮助,加油。一、查询条件包含or,可能导致索引失效新建一个user表,它有一......
  • 【云原生】Elasticsearch + kibana on k8s 讲解与实战操作
    目录一、概述二、Elasticsearch编排部署1)添加源并下载编排部署包2)构建镜像3)修改yaml编排4)开始部署5)测试验证6)elasticsearch-head7)卸载三、Kibana编排部署1)添加源并下载编......
  • elasticsearch聚合查询之排序
    排序默认只能按两个字段排序:_count和_key 如果想按二次聚合结果中的字段排序语法如下: GEThow2java/product/_search//求每个地方商品数量,并按平均价格从高往低排......