ES learning-java Operation 2.4. version 0

Source: Internet
Author: User
Tags stub

Package Esjava;

Import org.elasticsearch.action.bulk.*;
Import Org.elasticsearch.action.delete.DeleteRequest;
Import Org.elasticsearch.action.delete.DeleteResponse;
Import Org.elasticsearch.action.fieldstats.FieldStats;
Import Org.elasticsearch.action.get.GetRequestBuilder;
Import Org.elasticsearch.action.get.GetResponse;
Import Org.elasticsearch.action.get.MultiGetItemResponse;
Import Org.elasticsearch.action.get.MultiGetResponse;
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.transport.TransportClient;
Import Org.elasticsearch.cluster.node.DiscoveryNode;
Import org.elasticsearch.common.settings.Settings;
Import org.elasticsearch.common.transport.InetSocketTransportAddress;
Import Org.elasticsearch.common.unit.ByteSizeUnit;
Import Org.elasticsearch.common.unit.ByteSizeValue;
Import Org.elasticsearch.common.unit.TimeValue;
Import Org.elasticsearch.common.xcontent.XContentBuilder;
Import Org.elasticsearch.common.xcontent.XContentFactory;

Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import java.net.UnknownHostException;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.concurrent.TimeUnit;

/**
* Created by Zhuzhiqiang on 2018/7/28.
*/
public class Esutile {
static Transportclient client;
Private Indexrequest source;
static {
map<string, string> map = new hashmap<string, string> ();
Map.put ("Cluster.name", "Es-cluster");
Settings.builder Settings = Settings.builder (). put (map);
try {
Client = Transportclient.builder (). settings (Settings). Build ()
. addtransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname ("192.168.0.108"), Integer.parseint (" 9300 ")));
} catch (Unknownhostexception e) {
E.printstacktrace ();
}
}

public static void TestInfo () {
list<discoverynode> nodes = Client.connectednodes ();
for (Discoverynode node:nodes) {
System.out.println (Node.gethostaddress ());
}
}

/**
* Organize JSON string, mode 1, direct stitching
*/
public static String CreateJson1 () {
String json = "{" +
"\" User\ ": \" kimchy\ "," +
"\" postdate\ ": \" 2013-01-30\ "," +
"\" message\ ": \" trying out elasticsearch\ "" +
"}";
return JSON;
}

/**
* Create JSON with map
*/
public static map<string, object> CreateJson2 () {
map<string,object> json = new hashmap<string, object> ();
Json.put ("User", "kimchyy");
Json.put ("Postdate", New Fieldstats.date ());
Json.put ("message", "trying out elasticsearch update");
return JSON;
}

Public Xcontentbuilder CreateJson4 () throws Exception {
Create a JSON object, one of the ways to create JSON
Xcontentbuilder Source = Xcontentfactory.jsonbuilder ()
. StartObject ()
. Field ("User", "Kimchy")
. Field ("Postdate", New Fieldstats.date ())
. Field ("Message", "trying to out ElasticSearch")
. EndObject ();
return source;
}

Add a document

public static void Creat () throws Exception {
String Json1 = CreateJson1 ();
Stored in the JSON in the index
Indexresponse response = Client.prepareindex ("Twitter", "tweet", "4"). SetSource (Json1). get ();
Results obtained
String index = Response.getindex ();
String type = Response.gettype ();
String id = response.getid ();
Long Version = Response.getversion ();
Boolean created = Response.iscreated ();
SYSTEM.OUT.PRINTLN (Index + ":" + Type + ":" + ID + ":" + version + ":" + created);
}

Update document

public static void Update () throws Exception {
Updaterequest updaterequest=new updaterequest ();
Updaterequest.index ("Twitter");
Updaterequest.type ("tweet");
Updaterequest.id ("3");
Updaterequest.doc (Xcontentfactory.jsonbuilder ()
. StartObject ()
Add to fields you don't have, replace existing fields
. Field ("Gender", "MALEWW"). EndObject ());
Updateresponse updateresponse = client.update (updaterequest). get ();
System.out.println (Updateresponse.getindex () + ":" +updateresponse.gettype () +
":" +updateresponse.getid () + ":" +updateresponse.getversion () + ":" +updateresponse.iscreated ()
);

}

Update document

public static void Updateandadd () throws Exception {
Set query criteria, add takes effect if not found
Indexrequest indexrequest = new Indexrequest ("Twitter", "tweet", "5")
. Source (Xcontentfactory.jsonbuilder ()
. StartObject ()
. Field ("Gender", "MALEWWQ")
. EndObject ());
Updaterequest updaterequest=new updaterequest ();
Updaterequest.index ("Twitter");
Updaterequest.type ("tweet");
Updaterequest.id ("5");
Updaterequest.doc (Xcontentfactory.jsonbuilder ()
. StartObject ()
Add to fields you don't have, replace existing fields
. Field ("User", "Zzq"). EndObject ());
Updateresponse updateresponse = client.update (Updaterequest.upsert (indexrequest)). get ();
System.out.println (Updateresponse.getindex () + ":" +updateresponse.gettype () +
":" +updateresponse.getid () + ":" +updateresponse.getversion () + ":" +updateresponse.iscreated ()
);

}


Delete
public static void Delete () throws Exception {
Deleteresponse deleteresponse = client.preparedelete ("Twitter", "tweet", "4"). get ();
System.out.println (Deleteresponse.getindex () + ":" +deleteresponse.gettype () +
":" +deleteresponse.getid () + ":" +deleteresponse.getversion () + ":" +deleteresponse.tostring ()
);

}

Inquire

public static void Search () throws exception{
GetResponse GetResponse = client.prepareget ("Twitter", "tweet", "3"). get ();
System.out.println (Getresponse.getsourceasstring ());


}
/**
* Test Multi Get API
* Get from different index, type, and ID
*/

public static void Testmultiget () {
Multigetresponse multigetresponse = Client.preparemultiget ()
. Add ("Twitter", "tweet", "1")
. Add ("Twitter", "tweet", "1", "3", "4")
. get ();

for (Multigetitemresponse itemresponse:multigetresponse) {
GetResponse response = Itemresponse.getresponse ();
if (response.isexists ()) {
String sourceasstring = response.getsourceasstring ();
System.out.println (sourceasstring);
}
}
}


/**
* Bulk Batch Execution
* One query can update or delete multiple document
*/

public void Testbulk () throws Exception {
Bulkrequestbuilder bulkrequest = Client.preparebulk ();
Bulkrequest.add (Client.prepareindex ("Twitter", "tweet", "1")
. SetSource (Xcontentfactory.jsonbuilder ()
. StartObject ()
. Field ("User", "Kimchy")
. Field ("Postdate", New Fieldstats.date ())
. Field ("Message", "trying out Elasticsearch")
. EndObject ()));
Bulkrequest.add (Client.prepareindex ("Twitter", "tweet", "2")
. SetSource (Xcontentfactory.jsonbuilder ()
. StartObject ()
. Field ("User", "Kimchy")
. Field ("Postdate", New Fieldstats.date ())
. Field ("Message", "another Post")
. EndObject ()));
Bulkresponse response = Bulkrequest.get ();
System.out.println (Response.getheaders ());
}

/**
* Use bulk Processor
* @throws Exception
*/

public void Testbulkprocessor () throws Exception {
Create a Bulkporcessor object
Bulkprocessor bulkprocessor = bulkprocessor.builder (client, new Bulkprocessor.listener () {
public void Beforebulk (long paramlong, bulkrequest parambulkrequest) {
TODO auto-generated Method Stub
}

Execution when an error occurs
public void Afterbulk (long paramlong, Bulkrequest parambulkrequest, Throwable paramthrowable) {
TODO auto-generated Method Stub
}

public void Afterbulk (long paramlong, Bulkrequest parambulkrequest, Bulkresponse parambulkresponse) {
TODO auto-generated Method Stub
}
})
1w Request Execution once bulk
. Setbulkactions (10000)
1GB Data Refresh once bulk
. Setbulksize (New Bytesizevalue (1, BYTESIZEUNIT.GB))
Fixed 5s must be refreshed once
. Setflushinterval (Timevalue.timevalueseconds (5))
Number of concurrent requests, 0 not concurrent, 1 concurrent allow execution
. setconcurrentrequests (1)
Set Backoff, execute after 100ms, maximum request 3 times
. Setbackoffpolicy (
Backoffpolicy.exponentialbackoff (Timevalue.timevaluemillis (100), 3))
. build ();

Add a single request
Bulkprocessor.add (New Indexrequest ("Twitter", "tweet", "1"));
Bulkprocessor.add (New Deleterequest ("Twitter", "tweet", "2"));

Shut down
Bulkprocessor.awaitclose (ten, timeunit.minutes);
Or
Bulkprocessor.close ();
}
}



ES learning-java Operation 2.4. version 0

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.