ElasticSearch创建索引报错:ElasticsearchStatusException[type=resource_already_exists_exception, reason=inde

ElasticSearch创建索引报错:ElasticsearchStatusException[type=resource_already_exists_exception, reason=indeElasticsearchStatusException[Elasticsearchexception[type=resource_already_exists_exception,reason=index[discusspost/3IyXwPzXQ06z7uwDN-z5Zw]alreadyexists]]

大家好,又见面了,我是你们的朋友全栈君。

笔记待改

报错:
ElasticsearchStatusException[Elasticsearch exception [type=resource_already_exists_exception, reason=index [discusspost/3IyXwPzXQ06z7uwDN-z5Zw] already exists]
]

情景再现

一句话来说,就是用testDeleteIndex()方法删除了叫做”discusspost”的索引后,又用testCreateIndex()创建了叫做”discusspost”的索引,并往该索引里插入了数据。然后在testCreateIndex()方法里的createIndex()方法处报错。


application.properties

# ElasticsearchProperties
elasticSearch.url=127.0.0.1:9200
elasticsearch.indices=discusspost

EsConfig

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;

@Configuration
public class EsConfig { 
   
    @Value("${elasticSearch.url}")
    private String esUrl;

    //localhost:9200 写在配置文件中就可以了
    @Bean
    RestHighLevelClient client() { 
   
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(esUrl)//elasticsearch地址
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

pom.xml

	<properties>
		<java.version>1.8</java.version>
		<elasticsearch.version>7.12.0</elasticsearch.version>
	</properties>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>

DiscussPost

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;

@Document(indexName = "discusspost", /*type = "_doc",*/ shards = 6, replicas = 3)
public class DiscussPost { 
   

    @Id
    private int id;

    @Field(type = FieldType.Integer)
    private int userId;

    // 互联网校招
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String title;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String content;

    @Field(type = FieldType.Integer)
    private int type;

    @Field(type = FieldType.Integer)
    private int status;

    @Field(type = FieldType.Date)
    private Date createTime;

    @Field(type = FieldType.Integer)
    private int commentCount;

    @Field(type = FieldType.Double)
    private double score;

	//get、set方法、toString方法
}

ElasticsearchTests

@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class ElasticsearchTests { 
   

    @Autowired
    private DiscussPostMapper discussMapper;

    @Autowired
    private DiscussPostRepository discussRepository;

    @Qualifier("client")
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${elasticsearch.indices}")
    String esIndices;

    @Test
    public void testExistsIndex() throws Exception { 
   
        System.out.println(existsIndex(esIndices));
    }

    @Test
    public void testCreateIndex() throws Exception { 
   
        System.out.println(createIndex(esIndices));
        //把所有帖子(List<DiscussPost>)存入es的discusspost索引(es的索引相当于数据库的表)
        discussRepository.saveAll(discussMapper.selectAllDiscussPosts());
    }

    @Test
    public void testDeleteIndex() throws Exception { 
   
        discussRepository.deleteAll();//删除所有数据
        System.out.println(deleteIndex(esIndices));
    }

    //判断索引是否存在
    public boolean existsIndex(String index) throws IOException { 
   
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }

    //创建索引
    public boolean createIndex(String index) throws IOException { 
   
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    //删除索引
    public boolean deleteIndex(String index) throws IOException { 
   
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }
}

完整报错信息

[discusspost/3IyXwPzXQ06z7uwDN-z5Zw] ElasticsearchStatusException[Elasticsearch exception [type=resource_already_exists_exception, reason=index [discusspost/3IyXwPzXQ06z7uwDN-z5Zw] already exists]
]
	at org.elasticsearch.rest.BytesRestResponse.errorFromXContent(BytesRestResponse.java:176)
	at org.elasticsearch.client.RestHighLevelClient.parseEntity(RestHighLevelClient.java:1933)
	at org.elasticsearch.client.RestHighLevelClient.parseResponseException(RestHighLevelClient.java:1910)
	at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1667)
	at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1639)
	at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1606)
	at org.elasticsearch.client.IndicesClient.create(IndicesClient.java:134)
	at com.nowcoder.community.ElasticsearchTests.createIndex(ElasticsearchTests.java:218)
	at com.nowcoder.community.ElasticsearchTests.testCreateIndex(ElasticsearchTests.java:197)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at java.util.ArrayList.forEach(ArrayList.java:1249)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at java.util.ArrayList.forEach(ArrayList.java:1249)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
	Suppressed: org.elasticsearch.client.ResponseException: method [PUT], host [http://127.0.0.1:9200], URI [/discusspost?master_timeout=30s&timeout=30s], status line [HTTP/1.1 400 Bad Request]
{"error":{"root_cause":[{"type":"resource_already_exists_exception","reason":"index [discusspost/3IyXwPzXQ06z7uwDN-z5Zw] already exists","index_uuid":"3IyXwPzXQ06z7uwDN-z5Zw","index":"discusspost"}],"type":"resource_already_exists_exception","reason":"index [discusspost/3IyXwPzXQ06z7uwDN-z5Zw] already exists","index_uuid":"3IyXwPzXQ06z7uwDN-z5Zw","index":"discusspost"},"status":400}
		at org.elasticsearch.client.RestClient.convertResponse(RestClient.java:326)
		at org.elasticsearch.client.RestClient.performRequest(RestClient.java:296)
		at org.elasticsearch.client.RestClient.performRequest(RestClient.java:270)
		at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1654)
		... 70 more

报错原因和解决方法

报错原因:分词器反复创建:先用standard分词器建的index,然后使用ik分词器又建索引出现这个错误,相当于对已有的index修改mapping,同样之前用standard建的索引,现在换成用ik分词器搜也搜不出来RestHighLevelClient的TermQuery。

解决方法:直接注释掉createIndex()方法,不创建索引就好了。你之前已经删除掉了索引”discusspost”,es里是没有”discusspost”索引的。但实体类”DiscussPost”里有”indexName = “discusspost””,你往索引里插入数据时,索引就自动存在了。

    @Test
    public void testCreateIndex() throws Exception { 
   
        //System.out.println(createIndex(esIndices));
        //把所有帖子(List<DiscussPost>)存入es的discusspost索引(es的索引相当于数据库的表)
        discussRepository.saveAll(discussMapper.selectAllDiscussPosts());
    }
    
    //创建索引
    public boolean createIndex(String index) throws IOException { 
   
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

我的疑问

问题:我用testDelete()方法把索引中的数据全部删掉,我用elasticsearch-head http://127.0.0.1:9100/刷新看了,数据确实都删掉了,然后用testInsert()方法插入一条数据,但此时,所有数据都插入了。

    //删除一条数据和删除所有数据
    @Test
    public void testDelete() { 
   
        //discussRepository.deleteById(109);//删除一条数据
        discussRepository.deleteAll();//删除所有数据
    }
    
    //一次保存一条数据
    @Test
    public void testInsert() { 
   
        //把id为241的DiscussPost的对象保存到discusspost索引(es的索引相当于数据库的表)
        discussRepository.save(discussMapper.selectDiscussPostById(241));
    }
    

问题:我用testDeleteIndex()删除所有数据再删除索引,我用elasticsearch-head http://127.0.0.1:9100/刷新看了,索引确实删掉了,然后用testInsert()方法插入一条数据,但此时,所有数据都插入了。

    @Test
    public void testDeleteIndex() throws Exception { 
   
        discussRepository.deleteAll();//删除所有数据
        System.out.println(deleteIndex(esIndices));
    }

    //删除索引
    public boolean deleteIndex(String index) throws IOException { 
   
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }


    //一次保存一条数据
    @Test
    public void testInsert() { 
   
        //把id为241的DiscussPost的对象保存到discusspost索引(es的索引相当于数据库的表)
        discussRepository.save(discussMapper.selectDiscussPostById(241));
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/158235.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Redmi路由器AC2100之Openwrt旁路由设置

    Redmi路由器AC2100之Openwrt旁路由设置一、思路和环境:1、Redmi路由器AC2100作为主路由,路由系统为Padavan,主要负责拨号、DHCP、WIFI等功能,网络地址为192.168.11.1。2、群晖虚拟机vmm安装koolshare的Openwrt,单臂软路由作为旁路由,以实现zerotier等插件功能,网络地址为192.168.11.11。3、将旁路由的网关指向主路由网络地址192.168.11.1,关闭DHCP和桥接;同时,将主路由的网关指向旁路由的网络地址192.168.11.11。通过主路由和旁路由互指网关实现。二、旁路由设置

    2022年6月5日
    155
  • 磁盘碎片整理软件评测

    磁盘碎片整理软件评测磁盘碎片整理软件评测选出适合你的软件 磁盘碎片整理软件大比评! 让系统自带碎片整理工具下岗,磁盘碎片整理软件大比评  硬盘在使用一段时间后,由于反复写入和删除文件,磁盘中的空闲扇区会分散到整个磁盘中不连续的物理位置上,从而使文件不能存在连续的扇区类。这样,再读写文件是就需要到不同的地方去读取,增加了磁头的来回移动,降低了磁盘的访问速度。硬盘就像屋子一

    2022年6月25日
    35
  • ENSP安装教程【手把手教学】「建议收藏」

    ENSP安装教程【手把手教学】「建议收藏」ENSP安装

    2022年10月14日
    2
  • 手机运行的python_运行python程序的两种方式

    手机运行的python_运行python程序的两种方式前言在手机上运行Python需要用一个软件,叫QPython3L,当然还有别的软件也是可以运行Python的,不过我认为QPython3L是其中相对较好的一个。首先声明一下,我也只是会简单的使用有了它,就可以实现用手机和电脑进行通信了,比如在手机用Socket给电脑发指令,电脑根据收到的指令去执行不同的函数。苹果手机有没有我也不知道,可以自己搜一下如何下载我是在酷安下的,直接搜索qpython3即…

    2022年8月12日
    5
  • pycharmhtml插件_pycharm使用技巧

    pycharmhtml插件_pycharm使用技巧“阅读本文大概需要3分钟。”写Python,很多朋友都用的PyCharm,包括我在内。但其实大部分情况下我们用到的功能可能仅仅占PyCharm功能的一小半都不到。本文推荐…

    2022年8月28日
    3
  • vsftpd安装包下载_vsftp搭建

    vsftpd安装包下载_vsftp搭建1、在profile文件中设置相关环境变量,允许使用代理上网,如果能联网则不需要配置主要为了能够使用第一种安装方式,如果不可行则可以使用第二种安装方式vi/etc/profile##在文件中加上以下配置信息,该配置为代理服务器地址,根据实际情况定义,该服务器地址必须可联网exporthttp_proxy=http://192.168.1.1:3128exporthttps_pro…

    2022年9月25日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号