Elasticsearch Java API Implementation Search sample

Source: Internet
Author: User

View cluster, Version:curl ' centos1:9200 '
Insert: Curl-xput ' http://localhost:9200/dept/employee/1 '-d ' {"EmpName": "Emp1"} '
View Index:curl ' Centos1:9200/_cat/indices?v '
View 1 Content: Curl ' Centos1:9200/dept/employee/1?pretty '
View all content: Curl ' centos1:9200/dept/employee/_search '
Easy search: Curl ' centos1:9200/dept/employee/_search?empname=emp1 '
Complex search: Curl ' centos1:9200/dept/employee/_search?pretty '-d ' {"Query": {"match": {"EmpName": "Emp2"}} '
Delete: Curl-xdelete ' http://172.16.1.16:9200/logstash-2016.02.* '

3.1 ES native API connection search (Java, non-restful connection instead of broadcast)
Description: Es cluster is very simple, as long as in the same LAN, more than one server can communicate with each other, and Cluster.name is the same, it can automatically set together.

Import Java.net.inetaddress;import Java.net.unknownhostexception;import Java.util.arraylist;import Java.util.collection;import Org.elasticsearch.action.search.searchresponse;import Org.elasticsearch.client.client;import Org.elasticsearch.client.transport.transportclient;import Org.elasticsearch.common.settings.settings;import org.elasticsearch.common.transport.InetSocketTransportAddress ; Import Org.elasticsearch.index.query.fuzzyquerybuilder;import Org.elasticsearch.index.query.MatchQueryBuilder; Import Org.elasticsearch.index.query.querybuilder;import Org.elasticsearch.index.query.querybuilders;import Org.elasticsearch.index.query.querystringquerybuilder;import Org.elasticsearch.index.query.RangeQueryBuilder; Import Org.elasticsearch.index.query.termquerybuilder;import Org.elasticsearch.index.query.TermsQueryBuilder; Import Org.elasticsearch.index.query.wildcardquerybuilder;import Org.elasticsearch.node.node;import Org.elasticsearch.node.nodebuilder;import Org.elasticsearch.search.SearchHIt;import org.elasticsearch.search.builder.searchsourcebuilder;/* Implement elasticsearch internal Java API ( Broadcast) * Refer * http://www.tuicool.com/articles/R7RVJb * https://www.elastic.co/guide/en/elasticsearch/client/ java-api/current/java-search.html * http://stackoverflow.com/questions/23520684/ elasticsearch-java-apinonodeavailableexception-no-node-available * Node Transport difference-http:// www.cnblogs.com/huangfox/p/3543134.html * */public class EsQuery01 {public static void main (string[] args) throws Excepti on {//1. Prepare transport//client Client = Buildclientbynode (); Client client = Buildclientbytransport ();//2. Prepare Query Paramquerybuilder QueryBuilder = Buildquery ();//3. Get responsesearchresponse response = Client.preparesearch ("dept"). Settypes ("Employee"). Setquery (Querybuil der). Setfrom (0). SetSize (2). Execute (). Actionget ();//searchresponse response = Client.preparesearch ( ). Execute (). Actionget (); if (response! = NULL) {SYSTEM.OUT.PRINTLN (response); for (Searchhit hit:response.getHits (). Gethits ()) {System.out.print (Hit.getid () + "~"); System.out.println (Hit.getsourceasstring ());}} else {System.out.println ("response null~~~");} if (client! = null) {Client.close ();}} /* Slow */public static Client Buildclientbytransport () throws unknownhostexception {final String clustername = "Es-cluste R ";        String str = "192.168.56.250";        string[] Ipstr = str.split ("\ \");        byte[] Ipbuf = new Byte[4];        for (int i = 0; i < 4; i++) {Ipbuf[i] = (byte) (Integer.parseint (Ipstr[i]) &0xff); }settings Settings = Settings.settingsbuilder (). Put ("Cluster.name", clustername). Build (); Client client = Transportclient.builder (). settings (Settings). Build (). addtransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname ("centos1"), 9300));//.addtransportaddress (new Inetsockettransportaddress (Inetaddress.getbyaddress (ipbuf), 9300)); return client;} /* Very slow */public static Client BUILDCLIentbynode () throws unknownhostexception {/* Run configurations > Arguments > VM Arguments, add "-des.path.home=/app l/elasticsearch-2.1.1 "*/final String clustername =" Es-cluster "; Node node = Nodebuilder.nodebuilder (). Settings (Settings.settingsbuilder (). Put ("http.enabled", false)). ClusterName ( clustername). Client (True). Node (); Client client = Node.client (); return client;} public static QueryBuilder Buildquery () {//termsquerybuilder QueryBuilder = Querybyids ();//fuzzyquerybuilder QueryBuilder = Querybuilders.fuzzyquery ("EmpName", "EMP"); Matchquerybuilder QueryBuilder = querybuilders.matchquery ("EmpName", "emp2");//wildcardquerybuilder QueryBuilder = Querybuilders.wildcardquery ("EmpName", "*emp*");//querystringquerybuilder QueryBuilder = Querybuilders.querystringquery (" -26");//full Textsearchsourcebuilder Searchsourcebuilder = new Searchsourcebuilder ( ); String json = Searchsourcebuilder.query (QueryBuilder). toString (); SYSTEM.OUT.PRINTLN (JSON); return QueryBuilder;} /* Refer https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html */public Static TermsQueryBuilder Querybyids () {Collection coll = new ArrayList (); Coll.add (1); Coll.add (2); Termsquerybuilder QueryBuilder = querybuilders.termsquery ("_id", coll); return QueryBuilder;}}


3.2  Manual restful Connection Search (Java)

Import Java.io.bufferedreader;import Java.io.dataoutputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Org.elasticsearch.index.query.matchquerybuilder;import Org.elasticsearch.index.query.querybuilders;import org.elasticsearch.search.builder.searchsourcebuilder;/* Implement RestFul Manually (FAST) * Refer * http://stackoverflow.com/questions/33889866/ How-to-send-url-request-with-json-to-elasticsearch-using-java * http://blog.csdn.net/dm_vincent/article/details/ 41693125 * */public class EsQuery02 {public static void main (string[] args) throws Exception {HttpURLConnection conn = nul L;dataoutputstream WR = null; BufferedReader br = null; StringBuilder Resultbuilder = new StringBuilder (); String line = null;try {//1. Prepare urlstring url01 = "Http://centos1:9200/dept/employee/_search?pretty";//2. Prepare query Param//string Queryparamjson = Buildqueryparambystr (); String Queryparamjson = Buildqueryparambyapi ();//3. Inject urlurl url = neW URL (URL01); conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("POST"); conn.setrequestproperty ("Content-type", "Application/json"); Conn.setrequestproperty ("Content-length", integer.tostring ( Queryparamjson.getbytes (). Length), Conn.setrequestproperty ("Content-language", "en-us"); Conn.setusecaches (False ); Conn.setdooutput (true);//4. Inject query PARAMWR = new DataOutputStream (Conn.getoutputstream ()); Wr.writebytes (Queryparamjson);//Connection                    Failure Handlingif (Conn.getresponsecode ()! =) {throw new RuntimeException ("Failed:http error code:")        + Conn.getresponsecode ()); }//5. Get Responsebr = new BufferedReader (New InputStreamReader ((Conn.getinputstream ())), while (line = Br.read        Line ()) = null) {resultbuilder.append (line); Resultbuilder.append (' \ R '); }system.out.println ("result~~~" + resultbuilder.tostring ());} catch (Exception e) {e.printstacktrace ();} finally {if (WR! = null) {Wr.close ();} if (br! = Null) {br.close ();} IF (conn! = null) {Conn.disconnect ();}}} public static String Buildqueryparambyapi () {Matchquerybuilder QueryBuilder = querybuilders.matchquery ("EmpName", " EMP2 "); Searchsourcebuilder Searchsourcebuilder = new Searchsourcebuilder (); String Queryparamjson = Searchsourcebuilder.query (QueryBuilder). toString (); System.out.println ("json~~~" + Queryparamjson); return Queryparamjson;} public static String Buildqueryparambystr () {/*curl ' Centos1:9200/dept/employee/_search?pretty '-d * ' {"query": {"match ": {" EmpName ":" Emp2 "}}} ' */string Queryparamjson =" {\ "query\": {\ "match\": {\ "empname\": \ "Emp2\"}} "; return Querypa Ramjson;}}


3.3 Jest RESTful connection search (Java)

Import Org.elasticsearch.index.query.matchquerybuilder;import Org.elasticsearch.index.query.querybuilders;import Org.elasticsearch.search.builder.searchsourcebuilder;import Io.searchbox.client.jestclientfactory;import Io.searchbox.client.config.httpclientconfig;import io.searchbox.client.http.jesthttpclient;/* Implement RestFul by Jest * Refer: * http://www.searchly.com/documentation/developer-api-guide/java-jest/* http://www.cnblogs.com/ huangfox/p/3542858.html * http://www.169it.com/article/13172689366007246587.html * Https://github.com/searchbox-io /jest/tree/master/jest * DOWNLOAD:HTTPS://OSS.SONATYPE.ORG/CONTENT/GROUPS/PUBLIC/IO/SEARCHBOX/JEST/2.0.2/* MVN: http://www.searchly.com/documentation/developer-api-guide/java-jest/* */public class EsQuery03 {/*string Connurl = " http://centos1:9200 ";p ublic static void Main (string[] args) {//1. Connectjestclient client = Getclient ();//2. Prepare Qu ery paramstring Queryparamjson = Buildqueryparambyapi ();//3. Searchsearchresult result =Search (client, Queryparamjson);//4. Get Responsegetcontent ();} public static Jestclient Getclient () {Jestclientfactory factory = new Jestclientfactory (); Factory.sethttpclientconfig ( New Httpclientconfig. Builder (Connurl). multithreaded (true). Build ()); Jestclient client = Factory.getobject (); return client;} public static string Buildqueryparambyapi (String queryparamjson) {Matchquerybuilder QueryBuilder = Querybuilders.matchquery ("EmpName", "EMP2"); Searchsourcebuilder Searchsourcebuilder = new Searchsourcebuilder (); Searchsourcebuilder.query (QueryBuilder); return Searchsourcebuilder.tostring ();} public static string Buildqueryparambystr () {string Queryparamjson = "{\" query\ ": {\" match\ ": {\" empname\ ": \" Emp2\ "}}} "; return Queryparamjson;} public static SearchResult Search (jestclient client, String Queryparamjson) {Search search = (search) New Search.builder (q        Ueryparamjson)//Multiple index or types can be added.  . Addindex ("dept"). AddType ("employee")      . build ();//jestresult result = Client.execute (search); SearchResult result = Client.execute (search); return result;} public static void GetContent () {//list<article> articles = Result.getsourceasobjectlist (article.class);//List <searchresult.hit<article, void>> hits = Searchresult.gethits (Article.class);} */}

Elasticsearch Java API Implementation Search sample

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.