Join the dependency
My local Elasticsearch version is 2.1.0, so join the corresponding Maven dependency
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>2.1.0</version></dependency>
Create Client
The Elasticsearch client is divided into node client and transportclient.
- Node Client: Nodes themselves are nodes of the Elasticsearch cluster, as well as nodes in the Elasticsearch cluster and other elasticsearch clusters
- Transportclient: Lightweight client, using Netty thread pool, socket connected to ES cluster. itself does not join the cluster, only as the processing of requests
Generally we use transportclient. Create an instance of the client as follows:
private TransportClient client = null; @Before public void createElaCLient() throws UnknownHostException { //如果集群是默认名称的话可以不设置集群名称 Settings settings = Settings.settingsBuilder().put("cluster.name","elasticsearch").build(); client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("master"),9300)); } /** * 关闭ela客户端 */ @After public void closeElaClient(){ if(client != null){ client.close(); } }
Client.transport.sniff sniffing function
You can set the Client.transport.sniff to true to allow the client to sniff the entire cluster state, the other machines in the cluster IP address added to the client, the advantage is that you do not manually set up all the clusters in the cluster IP to the connection client, it will automatically help you to add, and automatically discover new join the cluster The machine. The code example is as follows:
private TransportClient client = null; @Before public void createElaCLient() throws UnknownHostException { //如果集群是默认名称的话可以不设置集群名称 Settings settings = Settings.settingsBuilder().put("cluster.name","elasticsearch").put("client.transport.sniff",true).build(); client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("master"),9300)); }
Note: When the ES server listens to using the intranet server IP and accesses the extranet IP, Do not use Client.transport.sniff to True, when Autodiscover uses the intranet IP to communicate, resulting in the inability to connect to the ES server, and directly using the Addtransportaddress method to specify the ES server
Test client connected to Elasticsearch cluster
The code is as follows:
@Test public void testConnection(){ List<DiscoveryNode> discoveryList = client.connectedNodes(); for(DiscoveryNode node : discoveryList){ System.out.println(node.getName()); } }
Create/delete index and type information
/** * CREATE INDEX */@Test public void CreateIndex () {if (client! = null) {client.admin (). Indi CES (). Create (New Createindexrequest ("Test_index")). Actionget (); }}/** * Clear index */@Test public void Clearindex () {Indicesexistsresponse indicesexistsresponse = Client.admin (). Indices (). Exists (new Indicesexistsrequest ("Test_index")). Actionget (); if (indicesexistsresponse.isexists ()) {client.admin (). Indices (). Delete (new Deleteindexrequest ("Test_index"). Act Ionget (); }}/** * Defines the mapping type of the index (mapping) */@Test public void defineindextypemapping () {try {XC Ontentbuilder builder = Xcontentfactory.jsonbuilder (); Builder.startobject (). StartObject ("Test"). StartObject ("Properties") . StartObject ("id"). Field ("Type", "Long"). Field ("Store", "yes"). EndObject (). StartObject ("name"). Fiel D ("Type", "string"). FiEld ("Store", "yes"). Field ("Index", "not_analyzed"). EndObject (). EndObject (). EndObject (). EndObject (); Putmappingrequest mappingrequest = requests.putmappingrequest ("Test_index"). Type ("Test"). Source (builder); Client.admin (). Indices (). putmapping (Mappingrequest). Actionget (); } catch (IOException e) {e.printstacktrace (); }}/** * Delete a type under index */@Test public void DeleteType () {if (client! = NULL) {CLI Ent.preparedelete (). Setindex ("Test_index"). SetType ("Test"). Execute (). Actionget (); } }
The index Mapping (Mapping) for a type is customized here, and the default ES automatically handles mapping of the data type: a long, a double floating-point number for an integer type, a string mapping of strings, and a time of Date,true or False to Boolean.
Note: For strings, es defaults to "analyzed" processing, that is, to do word segmentation, remove stop words and other processing index. If you need to put a string as a whole to be indexed, this field needs to be set: Field ("Index", "not_analyzed").
Index data
/** * Bulk Index */@Test public void Indexdata () {Bulkrequestbuilder Requestbuilder = Client.preparebu LK (); for (person person:personlist) {String obj = getindexdatafromhotspotdata (person); if (obj! = null) {Requestbuilder.add (Client.prepareindex ("Test_index", "Test", String.valueof (Person.getid ())) . Setrefresh (True). SetSource (obj)); }} bulkresponse Bulkresponse = Requestbuilder.execute (). Actionget (); if (Bulkresponse.hasfailures ()) {iterator<bulkitemresponse> it = bulkresponse.iterator (); while (It.hasnext ()) {Bulkitemresponse itemresponse = It.next (); if (itemresponse.isfailed ()) {System.out.println (Itemresponse.getfailuremessage ()); }}}}/** * Single index data * @return */@Test public void Indexhotspotdata () { String Jsonsource = Getindexdatafromhotspotdata (new Person (1004, "Jim")); if (Jsonsource! = null) {Indexrequestbuilder Requestbuilder = Client.prepareindex ("Test_index", "Test"). Setrefresh (True); Requestbuilder.setsource (Jsonsource). Execute (). Actionget (); }} public String Getindexdatafromhotspotdata (person p) {string result = NULL; if (P! = null) {try {Xcontentbuilder builder = Xcontentfactory.jsonbuilder (); Builder.startobject (). Field ("id", P.getid ()). Field ("Name", P.getname ()). EndObject (); result = Builder.string (); } catch (IOException e) {e.printstacktrace (); }} return result; }
Querying data
ES support paging query to get data, can also get a lot of data at once, need to use scroll Search,querybuilder is a query condition
public List<Long> searchData(QueryBuilder builder){ List<Long> ids = new ArrayList<>(); SearchResponse response = client.prepareSearch("test_index").setTypes("test").setQuery(builder).setSize(10).execute().actionGet(); SearchHits hits = response.getHits(); for(SearchHit hit : hits){ Long id = (Long) hit.getSource().get("id"); ids.add(id); } return ids; }
Elasticsearch Java API Introduction