Distributed search ElasticSearch cluster creation and simple search instance applications

Source: Internet
Author: User

Distributed search ElasticSearch cluster creation and simple search instance applications

ElasticSearch is not introduced. Distributed ElasticSearch cluster construction method.


1. Create an embedded elasticsearch Node in the program to make it a part of the elasticsearch cluster, and then use this Node to communicate with the elasticsearch cluster.

/** When running the test instance, the corresponding index database datum has been created locally */
Public static void main (String [] args ){

// When you start a node, it automatically joins the elasticsearch cluster in the same network segment. The premise is that the elasticsearch cluster name (cluster. name) parameter must be set to the same.
String clusterName = "elasticsearch_pudp"; // cluster node name

/**
* If a node is started by default, the es cluster will automatically allocate some index shards to it. If you want this node to be used only as a client without storing data,
* You can set node. data to false or node. client to true.
*/
Node node = NodeBuilder. nodeBuilder (). clusterName (clusterName). client (true). node ();

// Start the node and add it to the specified cluster
Node. start ();

// Obtain the node search end. Use prepareGet to search for the datum index database with the index type datum. The unique id value of the index record is 150 records.
GetResponse response = node. client (). prepareGet ("datum", "datum", "" 00001500000.exe cute (). actionGet ();

// Object ing model
ObjectMapper mapper = new ObjectMapper ();
// Convert the value in the response of the search result to the specified object Model. Datum is a consulting Model object created by yourself.
Datum datum = mapper. convertValue (response. getSource (), Datum. class );

// Print the corresponding attributes of the object obtained in the search result
System. out. println ("news title:" + datum. getTitle ());

// Close the node
Node. close ();
}

Program running result:

News Title: Which of the following is better for the treatment of thrombosis?

Another case is that you do not want to add a node to a cluster. Instead, you only want to use it for unit testing. You need to start a local elasticsearch instance, here, "local" refers to running at the jvm level, that is, two different es nodes will form a cluster when running in the same JVM. It needs to set the local parameter of the node to true.

Node node = NodeBuilder. nodeBuilder (). local (true). node ();

2. Use the TransportClient interface to communicate with the es cluster.

Binding nodes in the Cluster

Through the TransportClient interface, we can communicate with the es cluster without starting the node. It needs to specify the IP address and port of one or more machines in the es cluster.

Client client = new TransportClient ()
. AddTransportAddress (new InetSocketTransportAddress ("192.168.0.149", 9300 ))
. AddTransportAddress (new InetSocketTransportAddress ("192.168.0.162", 9300 ));

Client. close ();

If you do not change the cluster name, the default cluster name is elasticsearch, which is located in the ElasticSearch. yml file under the elasticsearch \ config \ directory.

################################### Cluster #### ###############################

# Cluster name identifies your cluster for auto-discovery. If you're running
# Multiple clusters on the same network, make sure you're using unique names.
#
Cluster. name: elasticsearch

Customize the cluster node name in the program

/** When running the test instance, the corresponding index database datum has been created locally */
Public static void main (String [] args ){

// Customize the cluster node name
String clusterName = "elasticsearch_pudongping ";

// Change the cluster node name in the program
Settings settings = ImmutableSettings. settingsBuilder ()
. Put ("cluster. name", clusterName). build ();

// Create a cluster and bind machines in the Cluster
TransportClient client = new TransportClient (settings );
Clients. addTransportAddress (new InetSocketTransportAddress ("192.168.0.149", 9300 ));
Client. addTransportAddress (new InetSocketTransportAddress ("192.168.0.162", 9300 ));

// Search
GetResponse response = client. prepareGet ("datum", "datum", "" + 130)
. Execute ()
. ActionGet ();

ObjectMapper mapper = new ObjectMapper ();
Datum datum = mapper. convertValue (response. getSource (), Datum. class );

System. out. println ("news title:" + datum. getTitle ());

// Close the node
Client. close ();
}

Program running result:

News Title: What are the efficacy of the main components of novogene?

Set Properties to enable the client to sniff the status of the entire cluster

You can set client. transport. sniff to true to enable the client to sniff the status of the entire cluster.

/**
* You can set client. transport. sniff to true to enable the client to sniff the status of the entire cluster,
* Add the ip addresses of other machines in the cluster to the client. Generally, you do not need to manually set the ip addresses of all clusters in the cluster to connect to the client,
* It will automatically help you add and automatically discover machines that are newly added to the cluster.
*/
Settings settings = ImmutableSettings. settingsBuilder ()
. Put ("client. transport. sniff", true). build ();
TransportClient client = new TransportClient (settings );

Instance application:

Use TransportClient to initialize the client and perform a simple search:

Package com. bbf. client;

Import java. util. ArrayList;
Import java. util. List;

Import org. codehaus. jackson. map. ObjectMapper;
Import org. elasticsearch. action. get. GetResponse;
Import org. elasticsearch. action. index. IndexResponse;
Import org. elasticsearch. action. search. SearchResponse;
Import org. elasticsearch. client. transport. TransportClient;
Import org. elasticsearch. common. settings. ImmutableSettings;
Import org. elasticsearch. common. settings. Settings;
Import org. elasticsearch. common. transport. InetSocketTransportAddress;
Import org. elasticsearch. index. query. QueryBuilder;
Import org. elasticsearch. index. query. QueryBuilders;
Import org. elasticsearch. search. SearchHit;
Import org. elasticsearch. search. SearchHits;
Import com. bbf. search. model. Datum;

/**
* Description:
*
* @ Author <a href = 'mailto: dennisit@163.com '> Cn. pudp (En. dennisit) </a> Copy Right since
*
* Com. bbf. client. ESClient. java
*
*/

Public class ESClient {


/** When running the test instance, the corresponding index database datum has been created locally */
Public static void main (String [] args ){


// Customize the cluster node name
String clusterName = "elasticsearch_pudongping ";

// Change the cluster node name in the program and Set client. transport. sniff to true to enable the client to sniff the status of the entire cluster.
Settings settings = ImmutableSettings. settingsBuilder ()
. Put ("cluster. name", clusterName). put ("client. transport. sniff", true). build ();

// Create a client object
TransportClient client = new TransportClient (settings );

// Initialize the node in the cluster of the client object and bind multiple ip addresses
// Client. addTransportAddress (new InetSocketTransportAddress ("192.168.0.149", 9300 ));
Client. addTransportAddress (new InetSocketTransportAddress ("192.168.0.162", 9300 ));


// Search by Id
GetResponse response = client. prepareGet ("datum", "datum", "" + 130)
. Execute ()
. ActionGet ();

// The query result is mapped to an object class.
ObjectMapper mapper = new ObjectMapper ();
Datum datum = mapper. convertValue (response. getSource (), Datum. class );

System. out. println ("info No.:" + datum. getId () + "\ t info title:" + datum. getTitle ());

// Construct the queryer query. The first parameter is the keyword to be queried, and the second parameter is the domain of the corresponding index type in the index library to be searched.
QueryBuilder query = QueryBuilders. multiMatchQuery ("EBP", "keyword ");
// The first parameter datum indicates the index database, the second parameter datum indicates the index type, and from indicates the start position size indicates the number of queried items, similar to limit3, 5 in mysql
SearchResponse searchResponse = client. prepareSearch ("datum"). setTypes ("datum" ).setquery(query).setfrom(32.16.setsize(52.16.exe cute (). actionGet ();

 
// Convert the search result to a list set object
List <Datum> lists = getBeans (searchResponse );

System. out. println ("Number of queried results:" + lists. size ());
For (Datum dtm: lists ){
System. out. println ("info No.:" + dtm. getId () + "\ t info title:" + dtm. getTitle ());
}

// Close the client
Client. close ();

}

/**
* Obtain the json string value from the queried record and convert it to a <code> Datum </code> object.
*
* @ Author <a href = 'mailto: dennisit@163.com '> Cn. pudp (En. dennisit) </a> Copy Right since 09:24:29
*
* @ Param response
* Query result set <code> GetResponse </code>
* @ Return
* Returns the <code> Datum </code> object.
*/
Public static Datum getResponseToObject (GetResponse response ){
ObjectMapper mapper = new ObjectMapper ();
Return mapper. convertValue (response. getSource (), Datum. class );
}


/**
* Encapsulate the queried object set into a List set.
*
* @ Author <a href = 'mailto: dennisit@163.com '> Cn. pudp (En. dennisit) </a> Copy Right since 02:31:26
*
* @ Param response
* @ Return
*/
Public static List <Datum> getBeans (SearchResponse response ){
SearchHits hits = response. getHits ();
ObjectMapper mapper = new ObjectMapper ();
List <Datum> datumList = new ArrayList <Datum> ();
For (SearchHit hit: hits ){
String json = hit. getSourceAsString ();
Datum dtm = new Datum ();

Try {
Dtm = mapper. readValue (json, Datum. class );
DatumList. add (dtm );
} Catch (Exception e ){
E. printStackTrace ();
}

}
Return datumList;
}

}

Program running result:

Information No.: 130 news title: What are the main components of jienuowei?
Number of queried results: 5
Information No.: 16 Information title: Can the medical insurance agent be reimbursed?
News No.: 11 News Title: What are the advantages of the treatment scope of eppe?
Information No.: 17 Information title: what is the role mechanism of eppe?
News No.: 12 News Title: What are precautions for use of eppe?
Information No.: 20 news title: Can I use eppup for a stroke?

Elasticsearch installation and usage tutorial

ElasticSearch configuration file Translation

ElasticSearch cluster creation instance

Build a standalone and server environment for distributed search ElasticSearch

Working Mechanism of ElasticSearch

ElasticSearch details: click here
ElasticSearch: click here

This article permanently updates the link address:

Related Article

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.