In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is mainly about "how to realize the JavaAPI of ElasticSearch". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to achieve the JavaAPI of ElasticSearch"!
(1) Overview
Some people say that the best way to learn a technology is official documentation, which is true for most technologies. But official documents are not necessarily suitable for everyone to read, such as a beginner, it is not appropriate for him to read the official documents of Spring directly. Today I will introduce the API application of ES in Java in conjunction with an official client document of ElasticSearch.
Official documents may not be easy to find. The address is directly given here:
Https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/index.html
You can choose your own version of the documentation to refer to. I choose version 7.6 here and choose Java High Level REST Client.
(2) Project build 2.1 introduce dependency
First of all, you need to create a project, not to mention the creation of a project, and introduce ES core dependencies:
Org.springframework.boot spring-boot-starter-data-elasticsearch
In order to prevent server-client conflicts caused by version problems, try to set the version of ES consistent with the server-side version you installed:
1.8 7.6.1
These dependencies will be introduced later with some json and web, as well as test operations:
Basic configuration of org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.alibaba fastjson 1.2.762.2 project
Write a configuration class to inject the restHighLevelClient object:
Configurationpublic class ElasticSearchConfig {@ Bean public RestHighLevelClient restHighLevelClient () {RestHighLevelClient client=new RestHighLevelClient (RestClient.builder (new HttpHost ("192.168.78.128", 9200, "http")); return client;}}
Entity classes will be used later, which is provided here:
@ Data@AllArgsConstructorpublic class User {private String name; private String address;}
The next operation is done in SpringBootTest, first through @ Autowired injection
RestHighLevelClient object @ SpringBootTestclass ElasticsearchdemoApplicationTests {@ Autowired private RestHighLevelClient restHighLevelClient;} (3) Index API
Or according to the order of learning ES grammar, find the index API, there are a lot of operations in API, I will mainly choose some important ones to talk about.
3.1 create an index
The main object to create the index is CreateIndexRequest
@ Testpublic void testCreateIndex () throws IOException {/ / create index CreateIndexRequest request=new CreateIndexRequest ("test_index"); CreateIndexResponse createIndexResponse = restHighLevelClient.indices () .create (request, RequestOptions.DEFAULT); System.out.println (createIndexResponse.isAcknowledged ());}
Create a CreateIndexRequest object, set relevant properties, such as number of slices, number of copies, timeout, and so on, and then create an index through restHighLevelClient to get a result response.
/ / set shard and replica request.settings (Settings.builder () .put ("index.number_of_shards", 3) .put ("index.number_of_replicas", 2)); 3.2get the index
Get an index, the main object is GetIndexRequest
@ Testpublic void testGetIndex () throws IOException {/ / get index GetIndexRequest request=new GetIndexRequest ("test_index"); GetIndexResponse getIndexResponse = restHighLevelClient.indices () .get (request, RequestOptions.DEFAULT); System.out.println (getIndexResponse);} 3.3 determine whether the index exists
GetIndexRequest is also used
@ Testpublic void testExistsIndex () throws IOException {/ / get index GetIndexRequest request=new GetIndexRequest ("test_index"); boolean exists = restHighLevelClient.indices () .exists (request, RequestOptions.DEFAULT); System.out.println (exists);} 3.4 delete index
The request object to delete the index is DeleteIndexRequest
@ Testpublic void testDeleteIndex () throws IOException {DeleteIndexRequest request=new DeleteIndexRequest ("test_index"); AcknowledgedResponse delete = restHighLevelClient.indices () .delete (request, RequestOptions.DEFAULT); System.out.println (delete.isAcknowledged ());}
The operation of the index can be realized through the graphical interface, and you can understand the addition, deletion and modification.
(4) document API
The API of a document is divided into single document processing and batch document processing. I will introduce the addition, deletion, modification and query of a single document and a batch document API.
4.1 create a document
When creating a document with syntax, it looks like this:
PUT http://ip:port/ index name / type name / document id {"name": "javayz", "address": "hz"}
The usage code goes like this: the request object is IndexRequest
@ Testpublic void testCreateDoc () throws IOException {/ / PUT http://ip:port/ index name / type name / document id User user=new User ("javayz", "hz"); IndexRequest request=new IndexRequest ("text_index"); request.id ("1"); request.source (JSON.toJSONString (user), XContentType.JSON); IndexResponse index = restHighLevelClient.index (request, RequestOptions.DEFAULT); System.out.println (index.status ());}
In fact, the two are very similar, which is why it is necessary to learn the basics of technology first. If you have a foundation, you can understand it at a glance.
4.2 get documentation
Get the document and determine whether it exists and write it together here. The request object is GetRequest:
@ Testpublic void testGetDoc () throws IOException {GetRequest request=new GetRequest ("text_index"); request.id ("1"); boolean exists = restHighLevelClient.exists (request, RequestOptions.DEFAULT); if (exists) {GetResponse documentFields = restHighLevelClient.get (request, RequestOptions.DEFAULT); String sourceAsString = documentFields.getSourceAsString (); System.out.println (sourceAsString);} else {System.out.println (exists);}} 4.3 Update document
The request object for updating the document is UpdateRequest
Testpublic void testUpdateDoc () throws IOException {UpdateRequest request=new UpdateRequest ("text_index", "1"); User user=new User ("javayz2", "hz"); request.doc (JSON.toJSONString (user), XContentType.JSON); UpdateResponse response = restHighLevelClient.update (request, RequestOptions.DEFAULT); System.out.println (response.status ());} 4.4 Delete the document
The request object to delete the document is DeleteRequest
@ Testpublic void testDeleteDoc () throws IOException {DeleteRequest request=new DeleteRequest ("text_index", "1"); DeleteResponse deleteResponse = restHighLevelClient.delete (request, RequestOptions.DEFAULT); System.out.println (deleteResponse.status ());} 4.5 batch creation of documents
BulkRequest is used to create documents in batches, which is very similar to a single unit, except that multiple requests are aggregated into a single bulk and submitted together.
@ Testpublic void testBulkRequest () throws IOException {BulkRequest request=new BulkRequest (); request.timeout ("10s"); ArrayList list=new ArrayList (); list.add (new User ("javayz1", "hz"); list.add (new User ("javayz2", "hz")) / / go to the add document list.stream () .forEach (x-> {request.add (new IndexRequest ("text_index"). Source (JSON.toJSONString (x), XContentType.JSON)) in the BulkRequest object; BulkResponse bulk = restHighLevelClient.bulk (request, RequestOptions.DEFAULT); System.out.println (bulk.status ());} (v) query API
The most commonly used query operations are match (fuzzy query) and term (precise query). This paper introduces the most commonly used query methods:
@ Testpublic void testSearch () throws IOException {SearchRequest request = new SearchRequest ("text_index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder (); / / matching condition MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery ("name", "javayz1"); searchSourceBuilder.query (matchQueryBuilder); request.source (searchSourceBuilder); SearchResponse search = restHighLevelClient.search (request, RequestOptions.DEFAULT); System.out.println (search) } at this point, I believe you have a deeper understanding of "how to achieve the JavaAPI of ElasticSearch". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.