Use of Java APIs in Elasticsearch 6.0
1: Create Elasticsearch client using Java API
PackageCom.search.elasticsearch;Importorg.elasticsearch.client.transport.TransportClient;Importorg.elasticsearch.common.settings.Settings;Importorg.elasticsearch.common.transport.TransportAddress;Importorg.elasticsearch.transport.client.PreBuiltTransportClient;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.InetAddress;Importjava.util.Properties; Public classElasticsearchconfig {Private Statictransportclient Client; Publictransportclient getelasticsearchclient () {Try{Settings Settings=Settings.builder (). Put ("Cluster.name", "My-eslearn")//the connected cluster name. put ("Client.transport.ignore_cluster_name",true)//if the cluster name is not correct, you can also connect. Build (); //Create clientClient =Newprebuilttransportclient (Settings). addtransportaddress (NewTransportaddress (Inetaddress.getbyname ("127.0.0.1"), 9300));//host and port number returnclient; } Catch(Exception e) {e.printstacktrace (); } return NULL; }}
2: Use client to create INDEX, some fields in index specify IK word breaker, etc.
Package Com.search.elasticsearch;
ImportOrg.elasticsearch.action.DocWriteResponse;ImportOrg.elasticsearch.action.admin.indices.analyze.AnalyzeRequestBuilder;Importorg.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;ImportOrg.elasticsearch.action.bulk.BulkItemResponse;ImportOrg.elasticsearch.action.bulk.BulkRequestBuilder;ImportOrg.elasticsearch.action.bulk.BulkResponse;ImportOrg.elasticsearch.action.get.GetResponse;Importorg.elasticsearch.action.index.IndexRequest;ImportOrg.elasticsearch.action.index.IndexResponse;ImportOrg.elasticsearch.action.search.SearchResponse;ImportOrg.elasticsearch.action.search.SearchType;Importorg.elasticsearch.action.update.UpdateRequest;ImportOrg.elasticsearch.action.update.UpdateResponse;Importorg.elasticsearch.client.IndicesAdminClient;Importorg.elasticsearch.client.Requests;Importorg.elasticsearch.client.transport.TransportClient;Importorg.elasticsearch.common.settings.Settings;Importorg.elasticsearch.common.transport.TransportAddress;ImportOrg.elasticsearch.common.xcontent.XContentBuilder;Importorg.elasticsearch.common.xcontent.XContentFactory;Importorg.elasticsearch.index.query.QueryBuilders;Importorg.elasticsearch.transport.client.PreBuiltTransportClient;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Value;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.InetAddress;Importjava.util.Date;Importjava.util.List;Importjava.util.Properties;ImportJava.util.ResourceBundle;Importjava.util.concurrent.ExecutionException;Import StaticOrg.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; Public classElasticsearchutil {Private Statictransportclient Client; PublicElasticsearchutil () { This. client=NewElasticsearchconfig (). Getelasticsearchclient ();//Use the above created goodthe client is added to the class. } //creates an index and assigns IK participles to certain fields in the index, and then uses IK participles to query the index later. Public voidCreateIndex ()throwsIOException {//Creating MappingsXcontentbuilder mapping =Xcontentfactory.jsonbuilder (). StartObject (). StartObject ("Properties") //. StartObject ("m_id"). Field ("type", "keyword"). EndObject ()
Title: Field name, type: Text Type Analyzer: type of Word breaker
. StartObject ("title"). Field ("Type", "Text"). Field ("Analyzer", "Ik_smart"). EndObject ()//The field is added, and the Ik_smart word breaker will be used when querying. StartObject ("Content"). Field ("Type", "Text"). Field ("Analyzer", "Ik_max_word"). EndObject (). EndObject (). EndObject (); //index: Index name Type: type name (you can define it yourself)Putmappingrequest Putmap = requests.putmappingrequest ("index"). Type ("type")). Source (mapping); //Create an indexClient.admin (). Indices (). Preparecreate ("index"). Execute (). Actionget (); //to add a map to an indexclient.admin (). Indices (). putmapping (Putmap). Actionget (); }}
This time the index is created, mapping cannot be dropped.
3: Add content to the index created in step up, including id,id cannot be duplicated
Public void throws IOException { = Client.prepareindex ("index", "type", "1")//index, type, id . SetSource (Jsonbuilder () . StartObject () . Field ("title", "title") //field, Value . field ("content", "content" ). endobject () ). get (); }
Use postman to query the index:
4: Update index, update the index just created, if the same ID will overwrite the content just now
Public void throws IOException, Executionexception, interruptedexception { // each time the add ID should be different, equivalent to the primary key in the data table, the same The words will be overwritten updateresponse response = client.update ( "index", "type", "1") . doc (Xcontentfactory.jsonbuilder () . StartObject () field ("title", "National anthem of the People's Republic of China, the national anthem is the most beautiful song" ) . Field ("content", "the national anthem of the People's Republic of China, the national anthem is the most pleasant song"). EndObject ()) ). get ();
Use postman to view the contents of the index
5: Query the index, because the word breaker is different, the word breaker will be queried for the content of the first word, and then in the sub-paragraph query.
Query sub-section content
Query Result:
To query the title sub-segment:
Query Result:
6: Add another piece of data to the index
Public void throws IOException { = Client.prepareindex ("index", "type", "2") . SetSource (Jsonbuilder () . StartObject () . Field("title", "The Chinese nation is a great nation"). field ("content", "The Chinese nation is a great nation") . EndObject () ). get (); }
To query the content of a field:
Results: Two data can be found, because the query content, "the national anthem of the People's Republic of China" for fine-grained division, containing the word "Chinese", two of the data contain "China".
To query the field title:
Query result: Only one piece of data, because coarse-grained participle is used for title
7:search API Operation:
public void Search () {
SearchResponse response1 = Client.preparesearch ("index1", "index")//Specify Multiple indexes
. Settypes ("Type1", "type")//Specify Type
. Setsearchtype (Searchtype.query_then_fetch)
. Setquery (Querybuilders.matchquery ("title", "National anthem of the People's Republic of China")//Query
. Setpostfilter (Querybuilders.rangequery ("age"). from (a) to ()//Filter
. Setfrom (0). SetSize. Setexplain (True)
. get ();
Long totalhits1= response1.gethits (). totalhits; Number of Hits
System.out.println (TOTALHITS1);
SearchResponse Response2 = Client.preparesearch ("index1", "index")//Specify Multiple indexes
. Settypes ("Type1", "type")//Specify Type
. Setsearchtype (Searchtype.query_then_fetch)
. Setquery (Querybuilders.matchquery ("Content", "national anthem of the People's Republic of China"))//Query
. Setpostfilter (Querybuilders.rangequery ("age"). from (a) to ()//Filter
. Setfrom (0). SetSize. Setexplain (True)
. get ();
Long totalHits2 = Response2.gethits (). totalhits; Number of Hits
System.out.println (TOTALHITS2);
}
8:get API Operation:
Public void get () { = client.prepareget ("index", "type", "1"). get (); Map<string, object> Source = Response.getsource (); Set<String> strings = source.keyset (); Iterator<String> Iterator = strings.iterator (); while (Iterator.hasnext ()) { System.out.println (Source.get (Iterator.next ())); } }
Java API Official document: Https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.0/java-docs-index.html
Use of the Elasticsearch 6.0java API