ElasticSearch1.7 Java API

Source: Internet
Author: User

public class Esutil {

private static transportclient client;

private static ResourceBundle resource = Resourcebundle.getbundle ("es");

/** Index Library Name */
private static String index = resource.getstring ("es.db");

/** Index Table name */
private static String type = Resource.getstring ("es.table");

/** cluster number of shards */
private static String Shards_str = resource.getstring ("Es.shards");

private static Integer shards = Integer.parseint (SHARDS_STR);

private static Searchrequestbuilder Searchrequestbuilder;

Get the cluster name
private static String clustername = resource.getstring ("Es.cluster.name");

Get the cluster ip/domain name
private static String hostname = resource.getstring ("Es.hostname");

Get the first node port number
private static String Port1 = resource.getstring ("Es.port.1");

Get the first node port number
private static String Port2 = resource.getstring ("es.port.2");


/**
* CREATE INDEX Write Elasticsearch
*
* @param jsonlist
* Jsonlist data to create the index
*/
public static void CreateIndex (List<jsonobject> jsonlist) {
Settings Settings = Immutablesettings.settingsbuilder ()
Client.transport.sniff=true
The client sniffs the entire cluster state, automatically adds the IP addresses of the other machines in the cluster to the client, and automatically discovers the newly added machines to the cluster.
. put ("Client.transport.sniff", true). Put ("client", True)//Connect only as a client
. put ("data", false). Put ("Cluster.name", clustername)//cluster name
. build ();
Client = new Transportclient (settings). addtransportaddress (new inetsockettransportaddress (hostname, Integer.parseint (PORT1)))//TCP
Connection Address
. addtransportaddress (new Inetsockettransportaddress (hostname, integer.parseint (PORT2)));
Searchrequestbuilder = Client.preparesearch (index);
try {
Create an index
for (int i = 0; i < jsonlist.size (); i++) {
Indexresponse indexresponse = Client.prepareindex (index, type, Jsonlist.get (i). getString ("id")). SetSource ( Jsonlist.get (i). toString ())
. Execute (). Actionget ();
if (indexresponse.iscreated ()) {
SYSTEM.OUT.PRINTLN ("created successfully!");
} else {
System.out.println ("Create failed! ");
}
}
Client.close ();
}
catch (Exception e) {
E.printstacktrace ();
}

}

/**
* Deleted based on index ID
*
* @param UIDs
* Index ID
*/
public static void Deleteindex (list<string> uids) {
Settings Settings = Immutablesettings.settingsbuilder ()
Client.transport.sniff=true
The client sniffs the entire cluster state, automatically adds the IP addresses of the other machines in the cluster to the client, and automatically discovers the newly added machines to the cluster.
. put ("Client.transport.sniff", true). Put ("client", True)//Connect only as a client
. put ("data", false). Put ("Cluster.name", clustername)//cluster name
. build ();
Client = new Transportclient (settings). addtransportaddress (new inetsockettransportaddress (hostname, Integer.parseint (PORT1)))//TCP
Connection Address
. addtransportaddress (new Inetsockettransportaddress (hostname, integer.parseint (PORT2)));
Searchrequestbuilder = Client.preparesearch (index);
for (int i = 0; i < uids.size (); i++) {
Deleteresponse dresponse = client.preparedelete (index, type, uids.get (i)). Execute (). Actionget ();
if (Dresponse.iscontextempty ()) {
System.out.println (Uids.get (i) + "Delete succeeded. ");
} else {
System.out.println (Uids.get (i) + "Delete failed");
}
}
}

/**
* Deleted by index name
*
* @param indexname
* Index Library name
*/
public static void Deleteindexlib (String indexname) {
Settings Settings = Immutablesettings.settingsbuilder ()
Client.transport.sniff=true
The client sniffs the entire cluster state, automatically adds the IP addresses of the other machines in the cluster to the client, and automatically discovers the newly added machines to the cluster.
. put ("Client.transport.sniff", true). Put ("client", True)//Connect only as a client
. put ("data", false). Put ("Cluster.name", clustername)//cluster name
. build ();
Client = new Transportclient (settings). addtransportaddress (new inetsockettransportaddress (hostname, Integer.parseint (PORT1)))//TCP
Connection Address
. addtransportaddress (new Inetsockettransportaddress (hostname, integer.parseint (PORT2)));
Searchrequestbuilder = Client.preparesearch (index);
Deleteindexresponse dresponse = Client.admin (). Indices (). Preparedelete (IndexName). Execute (). Actionget ();
if (Dresponse.iscontextempty ()) {
System.out.println (indexname + "Delete succeeded. ");
} else {
System.out.println (indexname + "Delete failed");
}
}

/**
* @param UID
* The index ID to update
* @param JSON
* JSON data to be updated
*/
public static void Updateindex (String uid, jsonobject JSON) {
Settings Settings = Immutablesettings.settingsbuilder ()
Client.transport.sniff=true
The client sniffs the entire cluster state, automatically adds the IP addresses of the other machines in the cluster to the client, and automatically discovers the newly added machines to the cluster.
. put ("Client.transport.sniff", true). Put ("client", True)//Connect only as a client
. put ("data", false). Put ("Cluster.name", clustername)//cluster name
. build ();
Client = new Transportclient (settings). addtransportaddress (new inetsockettransportaddress (hostname, Integer.parseint (PORT1)))//TCP
Connection Address
. addtransportaddress (new Inetsockettransportaddress (hostname, integer.parseint (PORT2)));
Searchrequestbuilder = Client.preparesearch (index);
Updaterequest updaterequest = new Updaterequest ();
Updaterequest.index (index);
Updaterequest.type (type);
Updaterequest.id (UID);
Updaterequest.doc (JSON);
try {
Updateresponse updateresponse = client.update (updaterequest). get ();
if (!updateresponse.iscreated ()) {
SYSTEM.OUT.PRINTLN (UID + "update Success");
} else {
SYSTEM.OUT.PRINTLN (uid + "update failed");
}
}
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
catch (Executionexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

/**
* Multi-field Query
*
* @param pageSize
* Page Size
* @param keyword
* Query Keywords
* @param columns
* Multiple indexed fields are not determined
* @return Map Collection map.put ("Dispage", dispage); Map.put ("Jsonlist",
* resultlist);
*/
public static map<string, object> query (integer pageSize, integer currentno, Searchparvo vo, String ... columns) {
Settings Settings = Immutablesettings.settingsbuilder ()
Client.transport.sniff=true
The client sniffs the entire cluster state, automatically adds the IP addresses of the other machines in the cluster to the client, and automatically discovers the newly added machines to the cluster.
. put ("Client.transport.sniff", true). Put ("client", True)//Connect only as a client
. put ("data", false). Put ("Cluster.name", clustername)//cluster name
. build ();
Client = new Transportclient (settings). addtransportaddress (new inetsockettransportaddress (hostname, Integer.parseint (PORT1)))//TCP
Connection Address
. addtransportaddress (new Inetsockettransportaddress (hostname, integer.parseint (PORT2)));
Searchrequestbuilder = Client.preparesearch (index);
hashmap<string, object> map = new hashmap<string, object> ();
Search Result set
list<jsonobject> resultlist = new arraylist<jsonobject> ();
QueryBuilder QB = NULL;
QueryBuilder qb_dept = null;
QueryBuilder qb_item = null;
QueryBuilder qb_subject = null;
QueryBuilder qb_regtype = null;
QueryBuilder qb_disway = null;
Boolquerybuilder QueryBuilder = Querybuilders.boolquery ();
if (Stringutils.isnotblank (Vo.gettitle ())) {
QB = Querybuilders.multimatchquery (Vo.gettitle (), columns);
Querybuilder.must (QB);
if (Stringutils.isnotblank (Vo.getdid ())) {
Qb_dept = Querybuilders.matchphrasequery ("d_id", Vo.getdid ());
Querybuilder.must (qb_dept);
}
if (Stringutils.isnotblank (Vo.getiid ())) {
Qb_item = Querybuilders.matchphrasequery ("i_id", Vo.getiid ());
Querybuilder.must (Qb_item);
}
if (Stringutils.isnotblank (Vo.getsid ())) {
Qb_subject = Querybuilders.matchphrasequery ("s_id", Vo.getsid ());
Querybuilder.must (Qb_subject);
}
if (Stringutils.isnotblank (Vo.getregtype ())) {
Qb_regtype = Querybuilders.matchphrasequery ("Registration_type", Vo.getregtype ());
Querybuilder.must (Qb_regtype);
}
if (Stringutils.isnotblank (Vo.getdisway ())) {
Qb_disway = Querybuilders.matchphrasequery ("Discount_way", Vo.getdisway ());
Querybuilder.must (Qb_disway);
}
} else {
QB = Querybuilders.matchallquery ();
Querybuilder.must (QB);
}
Searchrequestbuilder.setquery (QueryBuilder);
SearchResponse response = Searchrequestbuilder.execute (). Actionget ();
Searchhits hits = Response.gethits ();
Total Records
Long total = Hits.totalhits ();
Calculate Total Pages
int totalpages = totalpage (1, pageSize, (int) total);
Location of each start
int start = (currentNo-1) * pageSize;
Add Highlight Field
Searchrequestbuilder.addhighlightedfield ("title");
Searchrequestbuilder.sethighlighterpretags ("<span style=\" color:red\ ">");
Searchrequestbuilder.sethighlighterposttags ("</span>");
Response = Searchrequestbuilder.setfrom (start). SetSize (PageSize). Execute (). Actionget ();
searchhit[] searchhits = Response.gethits (). hits ();
Encapsulating Paging Object Information
Pagedresult dispage = new Pagedresult ();
Dispage.settotal (total);
Dispage.setpages (TotalPages);
Dispage.setpageno (CURRENTNO);
Dispage.setpagesize (pageSize);
for (Searchhit searchhit:searchhits) {
map<string, object> dd = Searchhit.getsource ();
Jsonobject json = (jsonobject) Jsonobject.tojson (DD);
Gets the specified field from the Set highlighted field
map<string, highlightfield> result = Searchhit.highlightfields ();
Highlightfield Titlefield = Result.get ("title");
if (Titlefield! = null) {
Get a defined highlight label
text[] titletexts = titlefield.fragments ();
Add a custom highlight label to the title string value
String title = "";
for (Text text:titletexts) {
Title + = text;
}
Json.put ("title", title);
}
Resultlist.add (JSON);
}
Map.put ("Dispage", dispage);
Map.put ("Jsonlist", resultlist);
return map;
}

/**
* @param currentno
* Current Page
* @param pageSize
* How many records are displayed on a page
* @param totalnum
* Total Records
* @return
*/
public static int Totalpage (integer currentno, integer pageSize, int totalnum) {
int totalpages = 0;
if (totalnum% pageSize = = 0) {
TotalPages = totalnum/pagesize;
} else {
TotalPages = totalnum/pagesize + 1;
}
return totalpages;
}
}

ElasticSearch1.7 Java API

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.