编程知识 cdmana.com

Java operation elasticsearch [Java high level rest clientedit]

1. sketch

  • Elasticsearch Is based on Lucene Developed a distributed full-text retrieval framework , towards Elasticsearch To store and retrieve from Elasticsearch Query in , The format is json.

  • towards Elasticsearch Medium storage data , In fact, to es Medium index Below type Storage in json Data of type .

  • elasticsearch It provides clients in many languages for operation elasticsearch service , for example : javapython.netJavaScriptPHP etc. . This article mainly introduces how to use java Language to operate elasticsearch service . stay elasticsearch There are two kinds of java Linguistic API , One is Java Transport Client, One is Java REST Client.

Java Transport Client** Is based on TCP Protocol interactive ,** stay elasticsearch 7.0+ After the version, the official does not approve of using it , stay Elasticsearch 8.0 Completely removed from the version of TransportClient

** Java REST Client Is based on HTTP Protocol interaction ,** and Java REST Client It is divided into Java Low Level REST Client and Java High Level REST Client

  • Java High Level REST Client Is in Java Low Level REST Client On the basis of the package , Make it more object-oriented and easy to operate elasticsearch service .

Official recommendation Java High Level REST Client , Because in practice , Java Transport Client In the case of large concurrency, the connection will be unstable . So let's take a look at elasticsearch Provided Java High Level REST Client ( Hereinafter referred to as advanced REST client ) Some basic operations of , With more operation, we read by ourselves elasticsearch Official documents of : [https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html)

2. Get ready

  • Environmental Science :

    • Windows 10
    • elasticsearch 7.91
    • IDEA
    • Maven
    • Java 8

Advanced clients need Java 1.8 And depend on Elasticsearch core project

  • rely on :
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.9.1</version>
        </dependency>

3. initialization

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));
  • The high-level client will internally create a low-level client for executing requests based on the provided generator . The low-level client maintains a connection pool and starts some threads , therefore , When you do a good job with the advanced client , You should close the advanced client , Then close the internal low-level client to release these resources . This can be done by Finish in the following time : close
client.close();

In relation to Java Advanced client in the rest of this document , The instance will be referenced as . RestHighLevelClient client <br /> Case study : 

  • Inquire about index Code :
public static void main(String[] args)  {
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(
                "127.0.0.1",  //es host  IP
                9200   // es  port http
                )
        );
        RestHighLevelClient client = new RestHighLevelClient(builder);
        GetRequest request = new GetRequest(
                "blog1", // Indexes 
                "1" // file ID
        );

        // When a get request is executed against a nonexistent index , Respond to 404 Status code , Will lead to IOException, It needs to be dealt with as follows :
        GetResponse documentFields = null;
        try {
            documentFields = client.get(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            //// Handle exceptions that are thrown because the index does not exist  
        }
        System.out.println(documentFields);
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
  • Query results :
{
	"_index": "blog1",
	"_type": "_doc",
	"_id": "1",
	"_version": 1,
	"_seq_no": 0,
	"_primary_term": 1,
	"found": true,
	"_source": {
		"age": 1,
		"country": "fuzhou",
		"date": "2020-09-10",
		"name": "ngitvusercancel"
	}
}

The above is a case study , Let's get to know through Java Advanced restful Client to access , Now we're going to talk about Api Introduction to

4. Indexes API (Index Api)

4.1 Create index (Create Index API)

4.1.1 Case study :

    /*
     *  Create index .
     * url:https://i-code.online/
     */
	public static void main(String[] args) {
        // Create link information 
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));

        // Create index request   The index name  student
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("student-1");

        // When you create an index, you can set the associated   Specific configuration 
        createIndexRequest.settings(Settings.builder()
                .put("index.number_of_shards",3) // Subdivision number 
                .put("index.number_of_replicas",2) // Number of backups 
        );
        // Create document type mapping 
        createIndexRequest.mapping("{\n" +
                "  \"properties\": {\n" +
                "    \"id\": {\n" +
                "      \"type\": \"long\",\n" +
                "      \"store\": true\n" +
                "    },\n" +
                "    \"name\": {\n" +
                "      \"type\": \"text\",\n" +
                "      \"index\": true,\n" +
                "      \"analyzer\": \"ik_max_word\"\n" +
                "    },\n" +
                "    \"content\": {\n" +
                "      \"type\": \"text\",\n" +
                "      \"index\": true,\n" +
                "      \"analyzer\": \"ik_max_word\"\n" +
                "    }\n" +
                "  }\n" +
                "}",
                XContentType.JSON  // Type mapping , What is needed is a JSON character string 
        );
        // Optional parameters 
        // Overtime , Wait for all nodes to be confirmed ( Use TimeValue The way )
        createIndexRequest.setTimeout(TimeValue.timeValueMinutes(1));

        try {
            // Synchronous execution 
            CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            // Back to CreateIndexResponse Allows you to retrieve information about the operation performed , As shown below :
            boolean acknowledged = createIndexResponse.isAcknowledged();// Indicates whether all nodes have acknowledged the request 
            boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();// Indicates whether the required number of shard copies for each fragment in the index was started before the timeout 
            System.out.println("acknowledged:"+acknowledged);
            System.out.println("shardsAcknowledged:"+shardsAcknowledged);
            System.out.println(createIndexResponse.index());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            // Close client link 
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The above is a index Creation process , Specific details of the operation api Here is a detailed explanation

4.1.2 Create index request

  • Need a parameter : CreateIndexRequestindex
CreateIndexRequest request = new CreateIndexRequest("twitter");//<1>

<1> To create an index

4.1.3 The index set

  • Each index created can have specific settings associated with it .
// Settings for this index 
request.settings(Settings.builder()
.put("index.number_of_shards", 3) // Subdivision number 
.put("index.number_of_replicas", 2)// Number of backups 
);

4.1.4 Index mapping

  • You can create an index , And create a mapping of its document type
request.mapping(
"{\n" +
"  "properties": {\n" +
"    "message": {\n" +
"      "type": "text"\n" +
"    }\n" +
"  }\n" +
"}", //<1>  The type to be defined 
XContentType.JSON); //<2>  This type of mapping , As  JSON  String provides 

<1> The type to be defined <2> This type of mapping , As JSON String provides

  • In addition to the example shown above , Mapping sources can also be provided in different ways : String
Map<String, Object> message = new HashMap<>();
message.put("type", "text");

Map<String, Object> properties = new HashMap<>();
properties.put("message", message);

Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);

request.mapping(mapping); // Accept map Mapping set of , Automatically turn to  json

Provides automatic conversion to JSON The mapping source of the format Map In this way, it's nested in layers , Pay attention to nesting in the process of use , The tags above are nested : properties -> message -> type

XContentBuilder builder = XContentFactory.jsonBuilder(); //  Use XContentBuilder Content generator 
builder.startObject();
{
    builder.startObject("properties");
    {
        builder.startObject("message");
        {
            builder.field("type", "text");
        }
        builder.endObject();
    }
    builder.endObject();
}
builder.endObject();

Mapping as a source provided by an object , Elastic search built-in helper , Used to generate JSON Content XContentBuilder

4.1.5 The index alias

  • Aliases can be set at index creation time
request.alias(new Alias("twitter_alias").filter(QueryBuilders.termQuery("user", "kimchy"))); // Alias to define 

4.1.6 Provide the whole source

  • We have set them step by step , In fact, it can also provide the whole source , Including all its parts ( mapping 、 Settings and aliases ):
request.source("{\n" +
        "    \"settings\" : {\n" +
        "        \"number_of_shards\" : 1,\n" +
        "        \"number_of_replicas\" : 0\n" +
        "    },\n" +
        "    \"mappings\" : {\n" +
        "        \"properties\" : {\n" +
        "            \"message\" : { \"type\" : \"text\" }\n" +
        "        }\n" +
        "    },\n" +
        "    \"aliases\" : {\n" +
        "        \"twitter_alias\" : {}\n" +
        "    }\n" +
        "}", XContentType.JSON);

As JSON The source provided by the string . It can also be used as or Provide .MapXContentBuilder

4.1.7 Optional parameters

  • You can choose to provide the following parameters :
request.setTimeout(TimeValue.timeValueMinutes(2));

Timeout to wait for all nodes to confirm index creation as TimeValue

request.setMasterTimeout(TimeValue.timeValueMinutes(1));

To act as TimeValue

request.waitForActiveShards(ActiveShardCount.from(2));
request.waitForActiveShards(ActiveShardCount.DEFAULT);

Creating index API Returns the number of active shards to wait for before responding , As in t Creating index API Returns the number of active shards to wait for before responding , As ActiveShardCount

4.1.8 Synchronous execution

  • Perform in the following manner when , The client will wait for return , And then continue to execute the code : CreateIndexRequest CreateIndexResponse
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

A synchronous call may raise At advanced level REST Unable to parse in the client REST Respond to 、 When the request will be sent or in a similar case there is no response returned from the server . IOException Return... On the server or In case of error code , The advanced client attempts to parse the response body error details , And then trigger generics , And add the original code to suppress exceptions . 4xx 5xx ElasticsearchExceptionResponseException

4.1.9 Asynchronous execution

  • It can also be executed asynchronously , So that the client can directly return . Users need to specify how to handle responses or potential failures by passing requests and listeners to asynchronous index creation methods : CreateIndexRequest
client.indices().createAsync(request, RequestOptions.DEFAULT, listener);

What is to be executed and used at the completion of execution CreateIndexRequest ActionListener

  • Asynchronous methods do not block and immediately return . After completion , If the execution is successful , Then use onResponse Method call , If execution fails , Then use onFailure The method . The failure scenario and expected exception are the same as the synchronous execution case . ActionListener <br /> A typical listener looks like this :
ActionListener<CreateIndexResponse> listener =
        new ActionListener<CreateIndexResponse>() {

    @Override
    public void onResponse(CreateIndexResponse createIndexResponse) {
        // Call on successful execution .
    }

    @Override
    public void onFailure(Exception e) {
        // Call when the whole fails 
    }
};

4.1.10 Create index response

  • Allows you to retrieve information about performing an operation , As shown below : CreateIndexResponse
boolean acknowledged = createIndexResponse.isAcknowledged(); // <1>
boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged(); // <2>

<1> Indicates whether all nodes have acknowledged the request

<2> Indicates whether to start the required number of shard copies for each fragment in the index before timing

4.2 Delete index (Delete Index Api)

4.2.1 Case study :

    /**
     *  Delete index .
     * url:https://i-code.online/
     * @param args
     */
    public static void main(String[] args) {
        //1.  Create client 
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));
        //2.  establish DeleteIndexRequest  Accept  index( Index name )  Parameters 
        DeleteIndexRequest request = new DeleteIndexRequest("student");
        // Timeout to wait for all nodes to confirm index deletion   Parameter is  TimeValue  type 
        request.timeout(TimeValue.timeValueMinutes(1));
        // Connect master The timeout of the node ( Use TimeValue The way )
        request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
        try {
            //  call delete
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            System.out.printf("isAcknowledged:%s", response.isAcknowledged());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.2.2 Delete index request

  • Need a parameter : DeleteIndexRequestindex
DeleteIndexRequest request = new DeleteIndexRequest("posts");//<1> <1>  Indexes (index) name 

<1> Indexes (index) name

4.2.3 Optional parameters

  • You can choose to provide the following parameters :
request.timeout(TimeValue.timeValueMinutes(2));
request.timeout("2m");

Timeout to wait for all nodes to confirm index deletion as TimeValue type

Timeout to wait for all nodes to confirm index deletion as String type

request.masterNodeTimeout(TimeValue.timeValueMinutes(1));// Connect master The timeout of the node ( Use TimeValue The way )
request.masterNodeTimeout("1m");// Connect master The timeout of the node ( Use string mode )

Connect master The timeout of the node ( Use TimeValue The way ) Connect master The timeout of the node ( Use string mode )

request.indicesOptions(IndicesOptions.lenientExpandOpen());

Settings control how unavailable indexes are resolved and how wildcard expressions are expanded IndicesOptions

4.2.4 Synchronous execution

  • Perform in the following manner DeleteIndexRequest when , The client will wait for DeleteIndexResponse return , And then continue to execute the code : DeleteIndexRequest DeleteIndexResponse
AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);

A synchronous call may raise At advanced level REST Unable to parse in the client REST Respond to 、 When the request will be sent or in a similar case there is no response returned from the server . IOException Return... On the server or In case of error code , The advanced client attempts to parse the response body error details , And then trigger generics , And add the original code to suppress exceptions .4xx 5xx ElasticsearchExceptionResponseException

4.2.5 Asynchronous execution

  • It can also be executed asynchronously , So that the client can directly return . The user needs to specify how to handle the response or potential failure by passing the request and listener to the asynchronous drop index method : DeleteIndexRequest
client.indices().deleteAsync(request, RequestOptions.DEFAULT, listener); //<1>

<1> What is to be executed and used at the completion of execution DeleteIndexRequest ActionListener

<br /> Asynchronous methods do not block and immediately return . After completion , If the execution is successful , Then use ActionListener#onResponse Method call , If execution fails , Then use ActionListener# onFailure The method . The failure scenario and expected exception are the same as the synchronous execution case .<br /> <br /> A typical listener looks like this :delete-index<br />

ActionListener<AcknowledgedResponse> listener =
        new ActionListener<AcknowledgedResponse>() {
    @Override
    public void onResponse(AcknowledgedResponse deleteIndexResponse) {
        // Call on successful execution .
    }

    @Override
    public void onFailure(Exception e) {
        // Call when the whole fails .DeleteIndexRequest
    }
};

4.2.6 Drop index response

  • Allows you to retrieve information about performing an operation , As shown below : DeleteIndexResponse
boolean acknowledged = deleteIndexResponse.isAcknowledged(); //<1>  Indicates whether all nodes have acknowledged the request 

<1> Indicates whether all nodes have acknowledged the request

  • If the index is not found , Will lead to : ElasticsearchException
try {
    DeleteIndexRequest request = new DeleteIndexRequest("does_not_exist");
    client.indices().delete(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException exception) {
    if (exception.status() == RestStatus.NOT_FOUND) {
        // If the index to delete is not found , Is to ""
    }
}

If the index to delete is not found , Is to ""

4.3 Index exists (Index Exists Api)

4.3.1 Case study :

    /**
     *  Whether the index exists Api
     * url:www.i-code.online
     * @param args
     */
    public static void main(String[] args) {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));
        // Create request 
        GetIndexRequest request = new GetIndexRequest("student");

        //<1>  Whether to return local information or retrieve status from the master node 
        request.local(false);
        //<2>  Return the result in a human friendly format 
        request.humanReadable(true);
        try {
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            System.out.println(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.3.2 Index exists request

  • senior REST Client side usage "Index Exists API". Index name is required . GetIndexRequest
GetIndexRequest request = new GetIndexRequest("twitter"); //<1> index  name 

<1> index name

4.3.3 Optional parameters

  • Index exists API The following optional parameters are also accepted , adopt : GetIndexRequest
request.local(false);//<1>  Whether to return local information or retrieve status from the master node 
request.humanReadable(true); //<2>  Return the result in a human friendly format 
request.includeDefaults(false); //<3>  Whether to return all default settings for each index 
request.indicesOptions(indicesOptions); //<4>  Controls how to resolve unavailable indexes and how to expand wildcard expressions 

<1> Whether to return local information or retrieve status from the master node <2> Return the result in a human friendly format <3> Whether to return all default settings for each index <4> Controls how to resolve unavailable indexes and how to expand wildcard expressions

4.3.4 Synchronous execution

  • Perform in the following manner when , The client will wait for return , And then continue to execute the code : GetIndexRequest boolean
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

Same as other synchronized

4.3.5 Asynchronous execution

  • It can also be executed asynchronously , So that the client can directly return . The user needs to specify how to handle the response or potential failure by passing the request and listener to the method where the asynchronous index exists : GetIndexRequest
client.indices().existsAsync(request, RequestOptions.DEFAULT, listener);//<1> What is to be executed and used at the completion of execution  GetIndexRequest  ActionListener

<1> What is to be executed and used at the completion of execution GetIndexRequest ActionListener Asynchronous processing logic is the same as other asynchronous ones , It's all about realizing ActionListener Methods

4.3.6 Respond to

  • The response is a value , Indicates the index ( Or index ) Whether there is . boolean

5. file Api (Document APIs)

5.1 Indexes API (Index Api)

5.1.1 Case study :

  • Add records
    private static void test02() {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));
        // Create request ,  Parameters index name 
        IndexRequest request = new IndexRequest("student");
        // The pattern of the request ,CREATE:  Create mode , Report an error if it already exists    Index: Being is no longer creating , Don't complain 
        request.opType(DocWriteRequest.OpType.INDEX);
        String json = "{\n" +
                "  \"id\": 12,\n" +
                "  \"name\": \"admin\",\n" +
                "  \"content\": \" Step processing logic is the same as other asynchronous , It's all about realizing ActionListener  Methods \"\n" +
                "}";
        request.id("1").source(
                json,
                XContentType.JSON
        );
        IndexResponse indexResponse = null;
        try {
            // call  index  Method 
            indexResponse = client.index(request, RequestOptions.DEFAULT);
            System.out.println(indexResponse.getVersion());
            System.out.println(indexResponse.getIndex());
            System.out.println(indexResponse.getId());
            System.out.println(indexResponse.status());
        } catch (ElasticsearchStatusException | IOException e) {
            e.printStackTrace();
        }
    }

5.1.2 Index request

  • The following parameters are required : IndexRequest
        // Create request ,  Parameters index name 
        IndexRequest request = new IndexRequest("student"); //<1> index  name 
        String json = "{\n" +
                "  \"id\": 12,\n" +
                "  \"name\": \"admin\",\n" +
                "  \"content\": \" Step processing logic is the same as other asynchronous , It's all about realizing ActionListener  Methods \"\n" +
                "}";
        request
        	.id("1") // <2>  Specify the document  ID 
            .source(
                json,
                XContentType.JSON // <3>  Specify parameter type ,json
        );

<1> index Name Index

<2> Requested documents ID

<3> Specify parameter type ,json

<br /> Provide document source <br />

  • In addition to the example shown above , Document sources can also be provided in different ways : String
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("id", 1);
jsonMap.put("name", "Admin);
jsonMap.put("content", " Step processing logic is the same as other asynchronous ");
IndexRequest indexRequest = new IndexRequest("student").id("1").source(jsonMap);

Document source as Automatic conversion to JSON Format Map

XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("id", 1);
builder.field("name", "admin);
builder.field("content", "trying out Elasticsearch");
}
builder.endObject();
IndexRequest indexRequest = new IndexRequest("student").id("1").source(builder);

Document sources are provided as objects , Elastic search built-in helper generation JSON Content XContentBuilder

IndexRequest indexRequest = new IndexRequest("student")
.id("1")
.source("id", 1,
"name", "admin",
"content", "trying out Elasticsearch");

As the document source provided by the key pair , The source will be converted to JSON Format Object

5.1.3 Optional parameters

  • You can choose to provide the following parameters :
request.routing("routing"); //<1>

<1> Route value

request.timeout(TimeValue.timeValueSeconds(1)); //<1>
request.timeout("1s");  // <2>

<1> Timeout to wait for the main slice As TimeValue <2> Timeout to wait for the main slice As String

request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); //<1>
request.setRefreshPolicy("wait_for"); //<2>

<1> Refresh the strategy For instance WriteRequest.RefreshPolicy <2> Refresh the strategy by String

request.version(2);

edition

request.versionType(VersionType.EXTERNAL); // Version type 

Version type

request.opType(DocWriteRequest.OpType.CREATE);//<1>
request.opType("create");//<2>

<1> The type of operation provided as a value DocWriteRequest.OpType <2> The type of operation provided can be or ( Default ) String create index

request.setPipeline("pipeline");

The name of the containing pipeline to be executed before indexing the document

5.1.4 Synchronous execution

  • Perform in the following manner when , The client will wait for return , And then continue to execute the code : IndexRequest IndexResponse
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
  • A synchronous call may raise At advanced level REST Unable to parse in the client REST Respond to 、 When the request will be sent or in a similar case there is no response returned from the server . IOException
  • Return... On the server or In case of error code , The advanced client attempts to parse the response body error details , And then trigger generics , And add the original code to suppress exceptions . 4xx 5xx ElasticsearchExceptionResponseException

5.1.5 Asynchronous execution

  • It can also be executed asynchronously , So that the client can directly return . Users need to specify how to handle responses or potential failures by passing requests and listeners to asynchronous index methods : IndexRequest
client.indexAsync(request, RequestOptions.DEFAULT, listener); //<1>

<1> What is to be executed and used at the completion of execution IndexRequest ActionListener

  • Asynchronous methods do not block and immediately return . After completion , If the execution is successful , Then use Method call , If execution fails , Then use The method . The failure scenario and expected exception are the same as the synchronous execution case . ActionListener onResponse onFailure
  • A typical listener looks like this :index
listener = new ActionListener<IndexResponse>() {
    @Override
    public void onResponse(IndexResponse indexResponse) {
        //<1>  Call on successful execution .
    }

    @Override
    public void onFailure(Exception e) {
        //<2>  Call when the whole fails .IndexRequest
    }
};

<1> Call on successful execution .

<2> Call when the whole fails .> IndexRequest

5.1.6 Index response

  • Allows you to retrieve information about performing an operation , As shown below : IndexResponse
String index = indexResponse.getIndex();
String id = indexResponse.getId();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
    //<1>
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
    //<2>
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
   // <3>
}
if (shardInfo.getFailed() > 0) {
    for (ReplicationResponse.ShardInfo.Failure failure :
            shardInfo.getFailures()) {
        String reason = failure.reason(); //<4>
    }
}

<1> Handle ( if necessary ) The first time the document was created

<2> Handle ( if necessary ) When a document is rewritten , Because it already exists

<3> When the number of successful slices is less than the total number of slices

<4> Dealing with potential failures

  • If there is a version conflict , Will lead to : ElasticsearchException
IndexRequest request = new IndexRequest("posts")
    .id("1")
    .source("field", "value")
    .setIfSeqNo(10L)
    .setIfPrimaryTerm(20);
try {
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
        //<1>
    }
}

<1> Throwing an exception indicates that a version conflict error is returned

  • Set to and already exists with the same index and ID In the case of documents , The same will happen : opTypecreate
IndexRequest request = new IndexRequest("posts")
    .id("1")
    .source("field", "value")
    .opType(DocWriteRequest.OpType.CREATE);
try {
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
    if (e.status() == RestStatus.CONFLICT) {
        //<1>
    }
}

<1> Throwing an exception indicates that a version conflict error is returned

5.2 obtain Api (Get API)

5.2.1 Case study :

    private static void test01(){
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200)));
        GetRequest request = new GetRequest("student");
        //  For specific fields   To configure    Source contains 
        String[] includs = {"name","id","content"};
        String[] excluds = {"id"};
        FetchSourceContext context = new FetchSourceContext(true,includs,excluds);

        request.id("1").version(2).fetchSourceContext(context);
        try {
            GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
            if (documentFields.isExists()) {
                // Search name 
                System.out.println(documentFields.getIndex());
                //  Get the source of the document  Map  result 
                System.out.println(documentFields.getSource());
                //  Get as a source  Map
                System.out.println(documentFields.getSourceAsMap());
                //  Get as a source  bytes
                System.out.println(documentFields.getSourceAsBytes());
            }else {
                System.out.println(" Yes, in the data ");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5.2.2 Get request

  • The following parameters are required :GetRequest
GetRequest getRequest = new GetRequest(
"posts", //<1>
"1");   //<1>

<1> The index name

<2> file ID

5.2.3 Optional parameters

  • You can choose to provide the following parameters :
request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);

Disable Source Retrieval , Enabled by default

String[] includes = new String[]{"message", "*Date"};
String[] excludes = Strings.EMPTY_ARRAY;
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);

For specific fields To configure Source contains

includes : The fields contained in the search results excludes : Fields excluded from the search results

String[] includes = Strings.EMPTY_ARRAY;
String[] excludes = new String[]{"message"};
FetchSourceContext fetchSourceContext =
new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);

Configure source exclusion for specific fields

request.storedFields("message");
GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
String message = getResponse.getField("message").getValue();

Configure retrieval for specific storage fields ( Require fields to be stored separately in the map )

Retrieve stored fields ( This field is required to be stored separately in the map )message

request.routing("routing");

Route value

request.preference("preference");

Preference values

request.realtime(false);

Set the real-time flag to ( By default )falsetrue

request.refresh(true);

Perform a refresh before retrieving the document ( By default )false

request.version(2);

edition

request.versionType(VersionType.EXTERNAL);

Version type

5.2.4 Synchronous execution

  • Perform in the following manner when , The client will wait for return , And then continue to execute the code : GetRequest GetResponse
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
  • A synchronous call may raise At advanced level REST Unable to parse in the client REST Respond to 、 When the request will be sent or in a similar case there is no response returned from the server .IOException

  • Return... On the server or In case of error code , The advanced client attempts to parse the response body error details , And then trigger generics , And add the original code to suppress exceptions .4xx5xxElasticsearchExceptionResponseException

5.2.5 Asynchronous execution

  • It can also be executed asynchronously , So that the client can directly return . Users need to specify how to handle responses or potential failures by passing requests and listeners to asynchronous fetch methods : GetRequest
client.getAsync(request, RequestOptions.DEFAULT, listener);

What is to be executed and used at the completion of execution GetRequest ActionListener

  • Asynchronous methods do not block and immediately return . After completion , If the execution is successful , Then use Method call , If execution fails , Then use The method . The failure scenario and expected exception are the same as the synchronous execution case .ActionListeneronResponseonFailure

  • A typical listener looks like this : get

ActionListener<GetResponse> listener = new ActionListener<GetResponse>() {
    @Override
    public void onResponse(GetResponse getResponse) {
        // Call on successful execution 
    }

    @Override
    public void onFailure(Exception e) {
        // Call when the whole fails .GetRequest
    }
};

5.2.6 Get a response

  • The returned document allows retrieval of the requested document, its metadata and the final stored field . GetResponse
String index = getResponse.getIndex();
String id = getResponse.getId();
if (getResponse.isExists()) {
    long version = getResponse.getVersion();
    String sourceAsString = getResponse.getSourceAsString();      // <1>  
    Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); // <2>
    byte[] sourceAsBytes = getResponse.getSourceAsBytes();          // <3>
} else {
    // <4>
}

<1> Retrieve the document as String <2> Retrieve the document as Map<String, Object> <3> Retrieve the document as byte[] <4> Dealing with scenarios where no documents can be found . Please note that , Although the response returned has a status code , But the return is valid , Instead of throwing an exception . This response does not save any source documents , Its method will return . 404 GetResponseisExistsfalse

  • When executing on a nonexistent index get When asked , The response has a status code , A raised request that needs to be processed as follows : 404 ElasticsearchException
GetRequest request = new GetRequest("does_not_exist", "1");
try {
    GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException e) {
    if (e.status() == RestStatus.NOT_FOUND) {
        //<1>  Handling throws an exception , Because the index doesn't exist 
    }
}

<1> Handling throws an exception , Because the index doesn't exist

  • If a specific document version is requested , And the existing documents have different version numbers , This will trigger a version conflict :
try {
    GetRequest request = new GetRequest("posts", "1").version(2);
    GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException exception) {
    if (exception.status() == RestStatus.CONFLICT) {
        // <1> 
    }
}

<1> Throwing an exception indicates that a version conflict error is returned

6. Conclusion

In fact, a lot of Api The use of is similar to the same , We don't have to deal with other things here Api To analyze , What you need to know can be viewed in the optical network document , The document address is on the rise .


This paper is written by AnonyStar Release , It can be reproduced, but the source of the original text should be stated .
Welcome to the wechat public account : Yunqi code Get more quality articles
More articles focus on the author's blog : Yunqi code i-code.online

版权声明
本文为[AnonyStar]所创,转载请带上原文链接,感谢

Scroll to Top