es2.x version of Javaapi usages

Source: Internet
Author: User
Tags string tags

Some time ago to do user tag system, the use of es2.2 to store queries. It involves the use of ES for JAVAAPI. Here to share some of the functions used by silly onions.

The first is an ES connection fetch operation instance.

Import Org.elasticsearch.action.search.SearchResponse;
Import org.elasticsearch.client.transport.TransportClient;
Import org.elasticsearch.common.settings.Settings;
Import org.elasticsearch.common.transport.InetSocketTransportAddress;
Import Org.elasticsearch.index.query.QueryBuilders;
Import Org.elasticsearch.search.aggregations.AggregationBuilders;

Import Org.elasticsearch.search.sort.SortOrder;
Import java.net.InetAddress;

Import java.net.UnknownHostException;
 /** * Created by CC on 2016/4/4. * * Public class Es_client {public static final String cluster_name = "razor_es";//instance name private static final Stri
    ng IP = "192.168.1.1";  private static final int PORT = 9300; Port//1. Set Cluster Name: Default is Elasticsearch, and set Client.transport.sniff to true to enable clients to sniff the entire cluster state, adding other machine IP in the cluster to the client//to ES2.0 effective priv
            ate static settings settings = settings. Settingsbuilder (). Put ("Cluster.name", Cluster_Name) . put ("Client.transport.sniff", true). BuilD ();


    Create a private object private static Transportclient client; Static {try {client = Transportclient.builder (). settings (Settings). Build (). ADDT
        Ransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname (IP), PORT));
        catch (Unknownhostexception e) {e.printstacktrace ();
    }//Get instance public static Transportclient Gettransportclient () {return client;
 }

}




Then there are some function actions:

Import Com.tesla.razor.dao.TagDAO;
Import com.tesla.razor.util.Es_Client;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
Import Org.elasticsearch.action.get.GetResponse;
Import Org.elasticsearch.action.search.SearchResponse;
Import Org.elasticsearch.index.query.BoolQueryBuilder;
Import Org.elasticsearch.index.query.QueryBuilders;
Import Org.elasticsearch.search.SearchHit;
Import Org.elasticsearch.search.aggregations.AggregationBuilders;

Import Org.elasticsearch.search.sort.SortOrder;
Import java.util.ArrayList;

Import java.util.List; public class Tagdaoimpl implements Tagdao {@Override public jsonobject getuserinfolist (String ProductID, String start
			Date, String stopdate) throws Exception {Boolquerybuilder Boolquerybuilder = Querybuilders.boolquery ();
			Boolquerybuilder.must (Querybuilders.matchquery ("product_id", ProductID));


		Boolquerybuilder.must (Querybuilders.rangequery ("LocalTime"). (StartDate). to (Stopdate); SearchResponse response = es_client.geTtransportclient (). Preparesearch ("Razor_cd"). Settypes ("Clientdata"). Setquery (Boolquerybuilder)/* AddAggreg ation (Aggregationbuilders.terms ("agg"). Field ("user_id"). Size () * * * Addaggregation (Aggregationbuil Ders.cardinality ("Agg1"). Field ("user_id"))//.addaggregation (Aggregationbuilders.daterange ("Range1"). Field ("Loc Altime "). AddRange (Startdate,stopdate)). AddSort (" LocalTime ", Sortorder.desc). SetSize (). Execute (). AC

		Tionget ();
		Jsonobject object=new jsonobject ();

		Object.put ("Total", response.getaggregations (). GetProperty ("Agg1.value"). toString ());
		Jsonarray arr = new Jsonarray ();
		Take the first 20 userid list<string> userids=new arraylist<string> ();
		Searchhit[] hits= response.gethits (). Gethits (); for (Searchhit hit:hits) {if (Userids.size () <20) {String UserID = Hit.getsource ().-Get ("user_id"). toString
				();
				int flag = 1;
		for (String s:userids) {if (S.equals (userid)) {				Flag = 0;
					Break
					} if (flag = 1)//flag 1 indicates that the user {Userids.add (userid) has not been logged;
				Arr.add (Hit.getsourceasstring ());
		}} object.put ("UserList", arr);
		System.out.println (object);
	return object; @Override Public Jsonobject Getuserinfolistbyid (String ProductID, String StartDate, String stopdate,string userid) t
			Hrows Exception {Boolquerybuilder boolquerybuilder = Querybuilders.boolquery ();
			Boolquerybuilder.must (Querybuilders.matchquery ("product_id", ProductID));
			Boolquerybuilder.must (Querybuilders.regexpquery ("user_id", ". *" + userid + ". *"));


		Boolquerybuilder.must (Querybuilders.rangequery ("LocalTime"). (StartDate). to (Stopdate); SearchResponse response = Es_client.gettransportclient (). Preparesearch ("Razor_cd"). Settypes ("Clientdata"). SetQue 
				RY (Boolquerybuilder)//Filter/*.addaggregation (aggregationbuilders.terms ("agg"). Field ("user_id"). Size (20) ) */Addaggregation (AggregatIonbuilders.cardinality ("Agg1"). Field ("user_id"). AddSort ("LocalTime", Sortorder.desc). SetSize. ex



		Ecute (). Actionget ();
		Jsonobject object=new jsonobject ();

		Object.put ("Total", response.getaggregations (). GetProperty ("Agg1.value"). toString ());
		Jsonarray arr = new Jsonarray ();
		Take the first 20 userid list<string> userids=new arraylist<string> ();
		Searchhit[] hits= response.gethits (). Gethits (); for (Searchhit hit:hits) {if (Userids.size () <20) {String user_id = Hit.getsource (). Get ("user_id"). Tostrin
				g ();
				int flag = 1;
						for (String s:userids) {if (S.equals (user_id)) {flag = 0;
					Break
					} if (flag = 1)//flag 1 indicates that the user {Userids.add (user_id) has not been logged;
				Arr.add (Hit.getsourceasstring ());

		}} object.put ("UserList", arr);
		System.out.println (object);
	return object; @Override Public Jsonobject Getuserinfolistbytags (string productid, String tags) throws ExceptiOn {string[] Tags_arr=tags.split (";");
		Boolquerybuilder Boolquerybuilder = Querybuilders.boolquery ();
		Boolquerybuilder.must (Querybuilders.matchquery ("product_id", ProductID)); for (String Tag:tags_arr) {if (Tag.contains ("C_channel_")) {Boolquerybuilder.must (Querybuilders.matchquery ("
			Channel_id ", tag.substring (10))); else if (Tag.contains ("c_provinc_")) {Boolquerybuilder.must (Querybuilders.matchquery ("Region", tag.substring (1
			0));
			else {boolquerybuilder.must (Querybuilders.matchquery ("App_tags.tag_name", tag));
				 } searchresponse response = Es_client.gettransportclient (). Preparesearch ("Razor_tag"). Settypes ("User_tag")


		. Setquery (Boolquerybuilder)//.addfield ("user_id"). SetSize (). Execute (). Actionget ();



		System.out.println (Response.tostring ());
		According to the query out of the user ID to clientdata two times query details Jsonobject object=new jsonobject ();

		Object.put ("Total", response.gethits (). Gettotalhits ()); Jsonarrayarr = new Jsonarray ();
		Take the first 20 userid list<string> userids=new arraylist<string> ();
		Searchhit[] hits= response.gethits (). Gethits (); for (Searchhit hit:hits) {<span style= "white-space:pre" > </span>......<span style= "White-space:pre" &G	T
	</span>} return object;  @Override public string Getuserdetailtags (String productid, String userid) throws Exception {GetResponse usertag=
		Es_client.gettransportclient (). Prepareget ("Razor_tag", "User_tag", UserID + "|" + ProductID). get ();
	return usertag.getsourceasstring (); @Override Public Jsonarray Getuserdetail (String ProductID, String StartDate, String stopdate,string userid) throws E
			xception {Boolquerybuilder Boolquerybuilder = Querybuilders.boolquery ();
			Boolquerybuilder.must (Querybuilders.matchquery ("product_id", ProductID));
			Boolquerybuilder.must (Querybuilders.regexpquery ("user_id", UserID)); Boolquerybuilder.must (Querybuilders.rangequery ("LocalTime"). From (STARtdate). to (Stopdate)); SearchResponse response = Es_client.gettransportclient (). Preparesearch ("Razor_cd"). Settypes ("Clientdata"). SetQue RY (Boolquerybuilder)//Filter. AddSort ("LocalTime", Sortorder.desc). SetSize. Execute (). Actionge




		T ();
		Map<string,list<string>> map=new hashmap<string, list<string>> ();

		Jsonarray arr = new Jsonarray ();
		Searchhit[] hits= response.gethits (). Gethits ();
		String tmp= "";

		int flag=1;
			for (Searchhit hit:hits) {System.out.println (hit.getsourceasstring ());
			Jsonobject jsonobject = new Jsonobject ();
			String Sessionid=hit.getsource (). Get ("session_id"). ToString ();
				if (flag==1)//represents taking the first record {Tmp=sessionid;
			flag=0;
				else {//Take the Record if (Tmp.equals (SessionID))//Repeat the SessionID immediately after 1th, enter the next loop {continue;
				else {Tmp=sessionid;
			}//1. Tim Clientdata Data Jsonobject.put for this session ("Clientdata", hit.getsourceasstring ()); 2. TimThis session of the Usinglog GetResponse usinglog= es_client.gettransportclient () prepareget ("Razor_usinglog", "Usinglog",
			UserID + "|" + SessionID). get ();
			Jsonobject.put ("Usinglog", usinglog.getsourceasstring ());  3. Add this session to the event GetResponse event= es_client.gettransportclient (). Prepareget ("Razor_event", "event", UserID + "|"
			+ SessionID). get ();

			Jsonobject.put ("Event", event.getsourceasstring ());
		Arr.add (Jsonobject);
	return arr; @Override public string Gettagtop (String ProductID) throws Exception {Boolquerybuilder Boolquerybuilder = Querybui
		Lders.boolquery ();
		Boolquerybuilder.must (Querybuilders.matchquery ("product_id", ProductID));


		Boolquerybuilder.must (Querybuilders.rangequery ("Add_time"). (StartDate). to (Stopdate); SearchResponse response = Es_client.gettransportclient (). Preparesearch ("Razor_tag"). Settypes ("User_tag"). SetQuer Y (Boolquerybuilder). Addaggregation (Aggregationbuilders.terms ("agg"). Field ("App_tags.tag_name"). Size). Addaggregation (Aggregationbuilders.cardinality (" Agg1 "). Field (" App_tags.tag_name ")


		. setSize (0). Execute (). Actionget ();
	return response.tostring ();
 }


	
}


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.