2
votes

The only way to setup Source and Settings using Java API is to use code like this(This is a simple test class with only one @test method):

   @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest

@TestPropertySource(value = "classpath:testApplication.properties")
public class ESJavaAPITests {


    @Value("${ES.cluster.name}")
    private String    CLUSTER_NAME;

    @Value("${ES.host}")
    private String    HOSTNAME;

    @Value("${ES.port}")
    private Integer   HOST_PORT;

    private static final String BOOK_INDEX_NAME ="bookshop";
    private static final String BOOK_TYPE_NAME ="book";

    private Client client(){
        Settings settings = Settings.settingsBuilder()
                .put("cluster.name", CLUSTER_NAME)
                .build();

        return new TransportClient.Builder().settings(settings).build()
                .addTransportAddress(
                        new InetSocketTransportAddress(
                                new InetSocketAddress(HOSTNAME, HOST_PORT))
                );

    }

    @Test
    public void shouldSaveDocToPredefinedShard() throws IOException {
        //delete all indexes if any
        client().admin().indices().prepareDelete("_all").get();


        CreateIndexResponse createIndexRequestBuilder = client().admin().indices()
                .prepareCreate(BOOK_INDEX_NAME)
                .setSettings(
                        Settings.settingsBuilder()
                                .put("index.number_of_shards", 2)
                                .put("index.number_of_replicas", 2)
                )
                .execute()
                .actionGet();

        IndexResponse response1 = client().prepareIndex(BOOK_INDEX_NAME, BOOK_TYPE_NAME, "id1")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                            .field("title", "Clean COde")
                            .field("author", "John Smith")
                        .endObject()
                )
                .setRouting("route1")
                .get();

        IndexResponse response2 = client().prepareIndex(BOOK_INDEX_NAME, BOOK_TYPE_NAME, "id2")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                            .field("title", "Learn Scala")
                            .field("author", "John Doe")
                        .endObject()
                )
                .setRouting("route2")
                .get();
    }
}

This works when I run it for the first time. But when I run it for the second time I get:

java.lang.IllegalStateException: Failed to load ApplicationContext

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:49) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74) 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:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl': Unsatisfied dependency expressed through method 'setBookRepository' parameter 0: Error creating bean with name 'bookRepository': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Mapper for [title] conflicts with existing mapping in other types: [mapper [title] has different [store] values]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookRepository': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Mapper for [title] conflicts with existing mapping in other types: [mapper [title] has different [store] values] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject

Why this seems to be a problem when I run this for the second time ?

How to create index and add two exemplary documents using:

  1. shard nr
  2. replica nr
  3. index name
  4. index type
  5. new document id.

    with Java API?


1

1 Answers

0
votes

There's not enough code here to explain the issue easily, but you have a repository class somewhere called "bookRepository" that is likely set up to auto configure. The repository is NOT getting deleted, so when you go to re-create the index the second time (second run), it's comparing the "book" class (assuming) against the schema of the existing ES index - and it's possible that you've made a change to the Title field.

You might be best off manually purging the books index (I'm assuming it's not critical, since you have a delete in your code above) and seeing if running the app twice in a row (your test case) still fails.