Elasticsearch Common Java API instances

Source: Internet
Author: User

1. Introduction of dependency

<dependency>            <groupId>org.springframework.data</groupId>            <artifactId> Spring-data-elasticsearch</artifactid>            <version>1.4.0.M1</version></dependency>

2: Create \ Add index

View Code

3. Create an entity class

PackageTestWeb;ImportOrg.springframework.data.elasticsearch.annotations.Document, @Document (indexname= "Yananindex", type= "Yanantype")PublicClassYanan {PrivateIntIdPrivateString name;PrivateString gender;PublicIntGetId () {ReturnId }Publicvoid SetId (Int ID) {this.id = ID;} public String GetName () {return< Span style= "COLOR: #000000" > name; } public void SetName ( String name {this.name = name;} public String Getgender () {return gender; } public void Setgender ( String gender) {this.gender = gender;}}     

The preparation is done, and the test begins below.

4.queryforobject\queryforlist\ aggregate query \ Statistics number \ Determine index existence \ Delete Index of specified ID

PackageTestWeb;ImportJava.util.List;ImportOrg.elasticsearch.action.search.SearchResponse;ImportOrg.elasticsearch.client.transport.TransportClient;ImportOrg.elasticsearch.common.settings.ImmutableSettings;ImportOrg.elasticsearch.common.settings.Settings;Importorg.elasticsearch.common.transport.InetSocketTransportAddress;Importorg.elasticsearch.common.transport.TransportAddress;ImportOrg.elasticsearch.index.query.BoolQueryBuilder;ImportOrg.elasticsearch.index.query.QueryBuilders;ImportOrg.elasticsearch.search.aggregations.AggregationBuilders;ImportOrg.elasticsearch.search.aggregations.Aggregations;Importorg.elasticsearch.search.aggregations.bucket.terms.StringTerms;ImportOrg.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;ImportOrg.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;ImportOrg.springframework.data.elasticsearch.core.ElasticsearchTemplate;ImportOrg.springframework.data.elasticsearch.core.ResultsExtractor;ImportOrg.springframework.data.elasticsearch.core.query.GetQuery;ImportOrg.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;PublicClassTestES {StaticTransportclient transportclient;StaticElasticsearchtemplate elasticsearchtemplate;PublicStaticvoidMain (string[] args) {elasticsearchtemplate=getelasticsearchtemplate ("localhost", "Elasticsearch_bak", 9303);//queryForObject ();//Querying documents based on index ID//queryForList ();//Aggregationquery ();//Aggregate queries//Count ();//Indexexists (Yanan.class);Deletebyid (); }PrivateStaticvoidDeletebyid () {//Indexquerybuilder indexquery=new Indexquerybuilder (). Withid ("1"). Withobject (Yanan.class);//String Delete = Elasticsearchtemplate.delete ("Yananindex", "Yanantype", "10");//ID of the index String delete = Elasticsearchtemplate.delete (Yanan.Class, "10");//ID of the index System.out.println (delete);//ID of the deleted index}PrivateStaticvoid Indexexists (class<yanan>Clazz) {If(Elasticsearchtemplate.indexexists (Clazz)) {System.out.println ("true"); }Else{System.out.println (False); } }PrivateStaticvoidCount () {Nativesearchquerybuilder searchquery=NewNativesearchquerybuilder (); Boolquerybuilder bqb =Querybuilders.boolquery (); Bqb.must (Querybuilders.termquery ("Gender", "female")); Searchquery.withindices ("Yananindex"). Withquery (BQB);Long Count =Elasticsearchtemplate.count (Searchquery.build ()); System.out.println (count); }PrivateStaticvoidAggregationquery () {Termsbuilder Termsbuilder = aggregationbuilders.terms ("Malecount"). Field ("Name"). Size (10); Nativesearchquerybuilder searchquery=NewNativesearchquerybuilder (); Boolquerybuilder bqb =Querybuilders.boolquery (); Bqb.must (Querybuilders.termquery ("Gender", "male")); Searchquery.withindices ("Yananindex"). Withquery (BQB). Addaggregation (Termsbuilder); Aggregations aggregations = Elasticsearchtemplate.query (Searchquery.build (),New resultsextractor<aggregations>() {@OverridePublicAggregations Extract (SearchResponse response) {ReturnResponse.getaggregations (); } }); Stringterms modelterms = (stringterms) aggregations.asmap (). Get ("Malecount"); list<bucket> buckets =Modelterms.getbuckets ();Forint i=0;i<buckets.size (); i++) {System.out.println (Buckets.get (i). GetKey () + "\ T" +Buckets.get (i). Getdoccount ()); } }PrivateStaticvoidqueryForList () {Nativesearchquerybuilder searchQuery =NewNativesearchquerybuilder (); Boolquerybuilder bqb =Querybuilders.boolquery (); Bqb.must (Querybuilders.termquery ("Gender", "male")); Searchquery.withindices ("Yananindex"). Withquery (BQB); list<yanan> list = Elasticsearchtemplate.queryforlist (Searchquery.build (), Yanan.Class);Forint i=0;i<list.size (); i++) {Yanan Yanan =List.get (i); System.out.println (Yanan.getname () + "\ T" +yanan.getgender () + "\ T" +Yanan.getid ()); } }PrivateStaticvoidqueryForObject () {getquery query =NewGetquery (); Query.setid ("1");//The ID of the index Yanan Yanan = elasticsearchtemplate.queryforobject (query, Yanan.Class); System.out.println (Yanan.getgender ()); System.out.println (Yanan.getname ()); System.out.println (Yanan.getid ());//ID of the entity}Static Elasticsearchtemplate getelasticsearchtemplate (String ip,string clustername,int port) {//<a href= "http://blog.csdn.net/ty4315/article/details/52434296"target=" _blank ">@ reference article 1</a>,<a href="http://blog.csdn.net/ljc2008110/article/details/48630609"target=" _blank ">@ reference article 2</a> Settings setting = Immutablesettings.settingsbuilder (). Put (" Cluster.name ", CLUSTERNAME)// Specify the cluster name. Put ("Client.transport.sniff", true) // Start sniffing, the client to sniff the entire cluster state and add the IP addresses of other machines in the cluster to the client, The advantage of this is that you do not have to manually set up all the clusters in the cluster IP to the connection client, it will automatically help you to add, and automatically discover the new cluster machine.  build (); // Create client to create via setting, if not specified, the default linked cluster name is Elasticsearch The link uses the TCP protocol 9303 transportclient = new Transportclient ( setting); Transportaddress transportaddress = new Inetsockettransportaddress (IP, port); Transportclient.addtransportaddresses (transportaddress); Elasticsearchtemplate = new Elasticsearchtemplate ( Transportclient); return Elasticsearchtemplate;}}     

Elasticsearch Common Java API instances

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.