In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "SpringBoot framework how to integrate ElasticSearch", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "SpringBoot framework how to integrate ElasticSearch" this article.
Dependence
SpringBoot version: 2.4.2
Org.projectlombok lombok true org.springframework.boot spring-boot-starter-data-elasticsearch org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools true True com.alibaba fastjson 1.2.47 org.springframework.cloud spring-cloud-dependencies 2020.0.1 pom import Com.alibaba.cloud spring-cloud-alibaba-dependencies 2021.1 pom import
First, learn how to operate es with curl.
Integrate with SpringBoot configuration class import org.elasticsearch.client.RestHighLevelClient;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.elasticsearch.client.ClientConfiguration;import org.springframework.data.elasticsearch.client.RestClients;import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration @ Configurationpublic class ElasticsearchConfig extends AbstractElasticsearchConfiguration {@ Override @ Bean public RestHighLevelClient elasticsearchClient () {final ClientConfiguration clientConfiguration = ClientConfiguration.builder () .connectedTo ("localhost:9200") .build (); return RestClients.create (clientConfiguration) .rest ();} entity class import lombok.Data;import org.springframework.data.annotation.Id;import org.springframework.data.elasticsearch.annotations.Document;import org.springframework.data.elasticsearch.annotations.Field Import org.springframework.data.elasticsearch.annotations.FieldType;@Data@Document (indexName = "product", shards = 3, replicas = 1) public class Product {/ / must have id, where id is a globally unique identity, equivalent to "_ id" @ Id private Long id in es / / unique identification of the product / * type: field data type * analyzer: word splitter type * index: whether to index (default: true) * Keyword: phrase, no word segmentation * / @ Field (type = FieldType.Text, analyzer = "ik_max_word") private String title;// commodity name @ Field (type = FieldType.Keyword) private String category / / Classification name @ Field (type = FieldType.Double) private Double price;// Product Price @ Field (type = FieldType.Keyword, index = false) private String images;// Picture address} Test example @ RestController@RequestMappingpublic class TestESController {@ Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; @ Resource ProductMapper productMapper @ GetMapping public void createIndex () {/ / create index, system initialization will automatically create index System.out.println ("create index");} @ DeleteMapping public void deleteIndex () {/ / create index, system initialization will automatically create index boolean flg = elasticsearchRestTemplate.deleteIndex (Product.class); System.out.println ("delete index =" + flg) } @ PostMapping public void save () {Product product = new Product (); product.setId (1L); product.setTitle ("Huawei Mobile"); product.setCategory ("Mobile"); product.setPrice (2999.0); product.setImages ("http://www.atguigu/hw.jpg"); Mobile (product)") } @ PutMapping public void update () {Product product = new Product (); product.setId (1L); product.setTitle ("Xiaomi 2 Mobile"); product.setCategory ("Mobile"); product.setPrice (9999.0); product.setImages ("http://www.atguigu/xm.jpg"); productMapper.save (product)" } @ GetMapping ("/ findById") public void findById () {Product product = productMapper.findById (1L). Get (); System.out.println (product);} @ GetMapping ("/ findAll") public void findAll () {Iterable products = productMapper.findAll (); for (Product product: products) {System.out.println (product) }} / / Delete @ DeleteMapping ("/ delDocument") public void delete () {Product product = new Product (); product.setId (1L); productMapper.delete (product);} / / add @ PostMapping ("/ addBatch") public void saveAll () {List productList = new ArrayList (); for (int I = 0; I)
< 10; i++) { Product product = new Product(); product.setId(Long.valueOf(i)); product.setTitle("["+i+"]小米手机"); product.setCategory("手机"); product.setPrice(1999.0+i); product.setImages("http://www.atguigu/xm.jpg"); productList.add(product); } productMapper.saveAll(productList); } //分页查询 @GetMapping("/findByPageable") public void findByPageable(){ //设置排序(排序方式,正序还是倒序,排序的 id) Sort sort = Sort.by(Sort.Direction.DESC,"id"); int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页 int pageSize = 5;//每页显示多少条 //设置查询分页 PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort); //分页查询 Page productPage = productMapper.findAll(pageRequest); for (Product Product : productPage.getContent()) { System.out.println(Product); } }}RestHighLevelClient直接操作 这些操作,就是javaApi,和上图中,通过http方式和es交互式类似的 索引操作/** * 这里时测试,开发时:通过 ESTemplate操作。Spring进行了封装 */@Slf4jpublic class ESIndexTestCase { public static void main(String[] args) throws IOException { // 创建客户端 RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200))); // 创建索引 // CreateIndexRequest indexRequest = new CreateIndexRequest("book"); // CreateIndexResponse indexResponse = esClient.indices().create(indexRequest, RequestOptions.DEFAULT); // boolean acknowledged = indexResponse.isAcknowledged(); // log.error("响应{}",acknowledged); // 查询索引 // GetIndexRequest getIndexRequest = new GetIndexRequest("book"); // GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT); // log.info("getAliases:{}",getIndexResponse.getAliases()); // log.info("getMappings:{}",getIndexResponse.getMappings()); // log.info("getSettings:{}",getIndexResponse.getSettings()); // 删除索引 AcknowledgedResponse deleteRes = esClient.indices().delete(new DeleteIndexRequest("book"), RequestOptions.DEFAULT); boolean delAck = deleteRes.isAcknowledged(); log.error("delAck:{}",delAck); esClient.close(); }}文档操作@Slf4jpublic class ESDocmentTestCase { public static void main(String[] args) throws IOException { // 创建客户端 RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200))); // 新增文档 // IndexRequest indexRequest = new IndexRequest("user"); // indexRequest.id("1001"); // // 准备文档 // User user = new User(); // user.setName("张三"); // user.setAge(22); // user.setSex("男"); // String userJson = JSONObject.toJSONString(user); // indexRequest.source(userJson, XContentType.JSON); // IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT); // log.error("getResult:==========>: {} ", indexResponse.getResult (); / / batch added documents BulkRequest bulkRequest = new BulkRequest (); bulkRequest.add (new IndexRequest (" user "). Id (" 2001 ") .source (XContentType.JSON," name "," Zhang San "," age "," 40 "," sex "," male ")) BulkRequest.add (new IndexRequest ("user"). Id ("2002") .source (XContentType.JSON, "name", "222"," age "," 10 "," sex "," female "); bulkRequest.add (new IndexRequest (" user "). Id (" 2003 ") .source (XContentType.JSON," name "," 33333 "," age "," 20 "," sex "," male ") BulkRequest.add (new IndexRequest ("user"). Id ("2004") .source (XContentType.JSON, "name", "111"," age "," 30 "," sex "," male "); bulkRequest.add (new IndexRequest (" user "). Id (" 2005 ") .source (XContentType.JSON," name "," 2222 "," age "," 31 "," sex "," female "); BulkResponse bulkResponse = esClient.bulk (bulkRequest, RequestOptions.DEFAULT) Log.error ("getResult:= >: {}", bulkResponse.getTook ()); / / Update document (full update, partial update) / / UpdateRequest updateRequest = new UpdateRequest ("user", "1001"); / / updateRequest.doc ("sex", "dddddd"); / / UpdateResponse updateResponse = esClient.update (updateRequest, RequestOptions.DEFAULT) / / log.error ("getResult:= >: {}", updateResponse.getResult ()); / / query the document according to _ id / / GetRequest getRequest = new GetRequest ("user", "1001"); / / GetResponse getResponse = esClient.get (getRequest, RequestOptions.DEFAULT); / / log.error ("getResult:= >: {}", getResponse.getSource ()) / / Delete data according to _ id / / DeleteRequest deleteRequest = new DeleteRequest ("user", "1001"); / / DeleteResponse deleteResponse = esClient.delete (deleteRequest, RequestOptions.DEFAULT); / / log.error ("getResult:= >: {}", deleteResponse.getResult ()); / / batch deletion (similar to batch addition) esClient.close () }} search operation @ Slf4jpublic class EsSearchTest {public static void main (String [] args) throws IOException {/ / create client RestHighLevelClient esClient = new RestHighLevelClient (RestClient.builder ("localhost", 9200)); / / query all / / SearchRequest searchRequest = new SearchRequest ("user"); / / SearchSourceBuilder queryBuilder = new SearchSourceBuilder () .query (QueryBuilders.matchAllQuery ()); / / queryBuilder.from (0) / / queryBuilder.size (4); / queryaBuilder.sort ("age", SortOrder.DESC); / / SearchRequest sourceRequest = searchRequest.source (queryBuilder); / / SearchResponse searchResponse = esClient.search (sourceRequest, RequestOptions.DEFAULT); / / log.error ("getHits:= > {}", searchResponse.getHits (). GetTotalHits ()); / / searchResponse.getHits (). ForEach (hit-> System.out.println (hit.getSourceAsString () / / 2-combination query / / SearchRequest searchRequest = new SearchRequest ("user"); / / BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery (); / here are the combination conditions. Similar to mysql where combination / / boolQueryBuilder.should (QueryBuilders.matchQuery ("age", "30")); / / boolQueryBuilder.should (QueryBuilders.matchQuery ("age", "40")); / / SearchSourceBuilder sourceBuilder = new SearchSourceBuilder (). Query (boolQueryBuilder); / / searchRequest.source (sourceBuilder); / / SearchResponse searchResponse = esClient.search (searchRequest, RequestOptions.DEFAULT) / / searchResponse.getHits () .forEach (hit-> System.err.println (hit.getSourceAsString (); / / 3-range query / / SearchRequest searchRequest = new SearchRequest ("user"); / / SearchSourceBuilder sourceBuilder = new SearchSourceBuilder (); / / RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery ("age"); / / rangeQuery.gte ("30"); / / sourceBuilder.query (rangeQuery) / / searchRequest.source (sourceBuilder); / / SearchResponse searchResponse = esClient.search (searchRequest, RequestOptions.DEFAULT); / / searchResponse.getHits () .forEach (hit-> System.out.println (hit.getSourceAsString ()); / / 4-Fuzzy query + highlight SearchRequest searchRequest = new SearchRequest ("user"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder (); FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery ("name", "Zhang San") SourceBuilder.query (fuzzyQuery); HighlightBuilder highlightBuilder = new HighlightBuilder (); highlightBuilder.preTags ("); highlightBuilder.postTags ("); highlightBuilder.field ("name"); sourceBuilder.highlighter (highlightBuilder); searchRequest.source (sourceBuilder); SearchResponse searchResponse = esClient.search (searchRequest, RequestOptions.DEFAULT); searchResponse.getHits (). ForEach (System.out::println) / / 5-aggregate query esClient.close ();}} these are all the contents of the article "how the SpringBoot Framework integrates ElasticSearch". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.