How to use Java High Level Rest Client with Spring Boot to talk to Elasticsearch 6.x

I rewrites source and test about ES 6.5.
https://github.com/maxmin93/spring-boot-java-highlevel-rest-client-elasticsearch

create new document to index ‘profile’ (type ‘person’)
// POST http://localhost:8080/api/v1/profiles
{
  "firstName": "Bob",
  "lastName": "Labla",
  "technologies": [
    { "name": "Angular 6", "yearsOfExperience": "1 year" }
  ],
  "emails": [ "bob@email.com" ]
}
update the document with id
// PUT http://localhost:8080/api/v1/profiles
{
  "id": "55fb8543-6bce-4478-bc7e-5df52e544dbe",
  "firstName": "Bob",
  "lastName": "Labla (A)",
  "technologies": [
    { "name": "Angular 6", "yearsOfExperience": "1 year" },
    { "name": "Javascript", "yearsOfExperience": "3 year" },
    { "name": "Java 8", "yearsOfExperience": "2 year" }
  ],
  "emails": [ "bob_new@email.com" ]
}
list all documents of index ‘profile’ (type ‘person’)

And I added some lines about checking index existence, creating index and list all indices.

    @PostConstruct
    public void checkIndexExists() throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices(INDEX);

        boolean exists = false;
        try {
            exists = client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e){
            log.info(String.format("es-index[%s] does not exists on connection.", INDEX));
        }

        if( !exists ){
            boolean isCreated = false;
            try {
                isCreated = createEsIndex(INDEX, TYPE);
            } catch (IOException e){
                log.info(String.format("es-index[%s]-type[%s] cannot be created.", INDEX, TYPE));
            }
            if( isCreated )
                System.out.println(String.format("es-index[%s]-type[%s] is created.", INDEX, TYPE));
        }

        System.out.println("# es-indices :");
        fetchIndices().forEach(r -> System.out.println("  - "+r.toString()));
    }

    // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-create-index.html
    private boolean createEsIndex(String index, String type) throws IOException {

        CreateIndexRequest request = new CreateIndexRequest(INDEX);
        request.settings(Settings.builder()
                .put("index.number_of_shards", 1)
                .put("index.number_of_replicas", 0)
        );
        // json data can be replaced "file.json" in resouces path
        request.mapping(TYPE,
                "{\n" +
                        "  \""+TYPE+"\": {\n" +
                        "    \"properties\": {\n" +
                        "      \"firstName\": {\"type\": \"text\"},\n" +
                        "      \"lastName\": {\"type\": \"text\"},\n" +
                        "      \"technologies\": {\"type\": \"nested\"}\n" +
                        "    }\n" +
                        "  }\n" +
                        "}",
                XContentType.JSON);

        final CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        final boolean acknowledged = response.isAcknowledged();
        return acknowledged;
    }

    // https://stackoverflow.com/a/52335626
    public List<String> fetchIndices() throws IOException {
        GetIndexRequest request = new GetIndexRequest().indices("*");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        String[] indices = response.getIndices();
        return Arrays.asList(indices);
    }

You can replace mapping setting to json file.

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Google photo

Google의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Twitter 사진

Twitter의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중

%d 블로거가 이것을 좋아합니다: