简体   繁体   中英

How to Use Elastic Search with Java version 6.5.1

what i need

  • i Need to Build Crud Insert Update Delete and Fetch data from Mysql.

I have look in to doc of Elastic search

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html

Which i did try some examples in Postman Rest client.

I have found link

https://www.javacodegeeks.com/2018/03/elasticsearch-tutorial-beginners.html

which work for Elastic 6.2.1

As 6.5.1 Pom.xml

                    <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
              <modelVersion>4.0.0</modelVersion>
              <groupId>org.elasticsearch</groupId>
              <artifactId>elasticsearch</artifactId>
              <version>6.5.1</version>
              <dependencies>
                <dependency>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch-core</artifactId>
                  <version>6.5.1</version>
                  <scope>compile</scope>
                </dependency>
                <dependency>
                  <groupId>org.elasticsearch.client</groupId>
                  <artifactId>elasticsearch-rest-high-level-client</artifactId>
                  <version>6.5.1</version>
                </dependency>
                <dependency>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch-secure-sm</artifactId>
                  <version>6.5.1</version>
                  <scope>compile</scope>
                </dependency>

Application.java

                    package com.javacodegeeks.example;

                import com.fasterxml.jackson.core.JsonProcessingException;
                import com.fasterxml.jackson.databind.ObjectMapper;
                import org.apache.http.HttpHost;
                import org.elasticsearch.ElasticsearchException;
                import org.elasticsearch.action.delete.DeleteRequest;
                import org.elasticsearch.action.delete.DeleteResponse;
                import org.elasticsearch.action.get.GetRequest;
                import org.elasticsearch.action.get.GetResponse;
                import org.elasticsearch.action.index.IndexRequest;
                import org.elasticsearch.action.index.IndexResponse;
                import org.elasticsearch.action.update.UpdateRequest;
                import org.elasticsearch.action.update.UpdateResponse;
                import org.elasticsearch.client.RestClient;
                import org.elasticsearch.client.RestHighLevelClient;
                import org.elasticsearch.common.xcontent.XContentType;
                import org.elasticsearch.client.*;

                import java.io.IOException;
                import java.util.HashMap;
                import java.util.Map;
                import java.util.UUID;

                public class Application {

                 //The config parameters for the connection
                 private static final String HOST = "localhost";
                 private static final int PORT_ONE = 9200;
                 private static final int PORT_TWO = 9201;
                 private static final String SCHEME = "http";

                 private static RestHighLevelClient restHighLevelClient;
                 private static ObjectMapper objectMapper = new ObjectMapper();

                 private static final String INDEX = "persondata";
                 private static final String TYPE = "person";

                 /**
                  * Implemented Singleton pattern here
                  * so that there is just one connection at a time.
                  * @return RestHighLevelClient
                  */
                 private static synchronized RestHighLevelClient makeConnection() {

                  if (restHighLevelClient == null) {
                   /*restHighLevelClient client = new RestHighLevelClient(
                           RestClient.builder(
                                   new HttpHost("localhost", 9200, "http"),
                                   new HttpHost("localhost", 9201, "http")));
                                   */
                   restHighLevelClient = new RestHighLevelClient(
                    RestClient.builder(
                     new HttpHost(HOST, PORT_ONE, SCHEME),
                     new HttpHost(HOST, PORT_TWO, SCHEME)));
                  }

                  return restHighLevelClient;
                 }

                 private static synchronized void closeConnection() throws IOException {
                  restHighLevelClient.close();
                  restHighLevelClient = null;
                 }

                 private static Person insertPerson(Person person) {
                  person.setPersonId(UUID.randomUUID().toString());
                  Map < String, Object > dataMap = new HashMap < String, Object > ();
                  dataMap.put("personId", person.getPersonId());
                  dataMap.put("name", person.getName());
                  IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, person.getPersonId())
                   .source(dataMap);
                  try {
                   IndexResponse response = restHighLevelClient.index(indexRequest);
                  } catch (ElasticsearchException e) {
                   e.getDetailedMessage();
                  } catch (java.io.IOException ex) {
                   ex.getLocalizedMessage();
                  }
                  return person;
                 }

                 private static Person getPersonById(String id) {
                  GetRequest getPersonRequest = new GetRequest(INDEX, TYPE, id);
                  GetResponse getResponse = null;
                  try {
                   getResponse = restHighLevelClient.get(getPersonRequest);
                  } catch (java.io.IOException e) {
                   e.getLocalizedMessage();
                  }
                  return getResponse != null ?
                   objectMapper.convertValue(getResponse.getSourceAsMap(), Person.class) : null;
                 }

                 private static Person updatePersonById(String id, Person person) {
                  UpdateRequest updateRequest = new UpdateRequest(INDEX, TYPE, id)
                   .fetchSource(true); // Fetch Object after its update
                  try {
                   String personJson = objectMapper.writeValueAsString(person);
                   updateRequest.doc(personJson, XContentType.JSON);
                   UpdateResponse updateResponse = restHighLevelClient.update(updateRequest);
                   return objectMapper.convertValue(updateResponse.getGetResult().sourceAsMap(), Person.class);
                  } catch (JsonProcessingException e) {
                   e.getMessage();
                  } catch (java.io.IOException e) {
                   e.getLocalizedMessage();
                  }
                  System.out.println("Unable to update person");
                  return null;
                 }

                 private static void deletePersonById(String id) {
                  DeleteRequest deleteRequest = new DeleteRequest(INDEX, TYPE, id);
                  try {
                   DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest);
                  } catch (java.io.IOException e) {
                   e.getLocalizedMessage();
                  }
                 }

                 public static void main(String[] args) throws IOException {

                  makeConnection();

                  System.out.println("Inserting a new Person with name testst...");
                  Person person = new Person();
                  person.setName("Testttt");
                  person = insertPerson(person);
                  System.out.println("Person inserted --> " + person);

                  System.out.println("Changing name to testst...");
                  person.setName("testst");
                  updatePersonById(person.getPersonId(), person);
                  System.out.println("Person updated  --> " + person);

                  System.out.println("Getting testst...");
                  Person personFromDB = getPersonById(person.getPersonId());
                  System.out.println("Person from DB  --> " + personFromDB);

                  System.out.println("Deleting teststss...");
                  deletePersonById(personFromDB.getPersonId());
                  System.out.println("Person Deleted");

                  closeConnection();
                 }
                }

Person.java

            package com.javacodegeeks.example;

        public class Person {

        private String personId;
        private String name;

        public String getPersonId() {
            return personId;
        }

        public void setPersonId(String personId) {
            this.personId = personId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return String.format("Person{personId='%s', name='%s'}", personId, name);
        }
        }

Can anyone suggest any tutorial which guide sample example with 6.5 version.

http://localhost:9200/

Json Output

            {
        name: "MIT22",
        cluster_name: "elasticsearch",
        cluster_uuid: "KMJcFFe9ST6H7bbir3OPzQ",
        version: {
        number: "6.5.1",
        build_flavor: "default",
        build_type: "zip",
        build_hash: "8c58350",
        build_date: "2018-11-16T02:22:42.182257Z",
        build_snapshot: false,
        lucene_version: "7.5.0",
        minimum_wire_compatibility_version: "5.6.0",
        minimum_index_compatibility_version: "5.0.0"
        },
        tagline: "You Know, for Search"
        }

Refrence

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html

https://www.elastic.co/blog/logstash-jdbc-input-plugin

https://github.com/jprante/elasticsearch-jdbc#quick-links

Thanks

Elasticsearch has its own official documentation with sufficient examples. You can start from here . The right side of the page give the complete content which covers almost everything you require to understand.

Since you will be using java application to perform CRUD operation, you will need to use elastic search high level rest client which is a java client to connect to elastic and perform CRUD. You can find the documentation here .

I you want to read detailed explanation about some topic the you can find the official definitive guide here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM