Elasticsearch 是一個開源的分散式 RESTful 搜尋和分析引擎,它使您可以快速,近乎實時地儲存,搜尋和分析大量資料,能夠解決越來越多不同的應用場景。
比如用作搜尋網路商店的商品,使用者的搜尋,交易資料的搜尋。業務的收集和儲存報表的分析在Springboot中如何使用elasticsearch去儲存和查詢資料呢,目前來說有以下幾種方式比較便捷:
REST ClientSpring DataSpring Data Elasticsearch Repositories本文將使用Spring Data Elasticsearch Repositories這種方式去訪問Elasticsearch。
準備需要自己搭建一臺Elasticsearch,elasticsearch的版本為7.7.0。本次Elasticsearch為單機版本Elasticsearch,生產環境要使用叢集版本。執行下面命令安裝
# 下載elasticsearch的rpmwget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.7.0-x86_64.rpmwget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.7.0-x86_64.rpm.sha512shasum -a 512 -c elasticsearch-7.7.0-x86_64.rpm.sha512 sudo rpm --install elasticsearch-7.7.0-x86_64.rpmsudo systemctl daemon-reloadsudo systemctl enable elasticsearch.servicesudo systemctl start elasticsearch.servic
修改es給其他ip訪問:
cluster.name: "docker-cluster"network.host: 0.0.0.0# custom confignode.name: "node-1"discovery.seed_hosts: ["127.0.0.1", "[::1]"]cluster.initial_master_nodes: ["node-1"]# 開啟跨域訪問支援,預設為falsehttp.cors.enabled: true# 跨域訪問允許的域名地址,(允許所有域名)以上使用正則http.cors.allow-origin: /.*/
Spring boot整合Elasticsearch在springboot的工程的pom檔案中引入elasticsearch的起步依賴spring-boot-starter-data-elasticsearch,如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>1234
在springboot的配置檔案application.properties檔案填寫elasticesearch的配置,這裡使用的9300埠,即使用TCP協議埠。
server.port=8500spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300spring.data.elasticsearch.cluster-name=my-application
和大多數spring-boot-starter-data-jpa類似,都是使用實體物件和資料庫的儲存結構欄位對應起來的。使用@Document(indexName = “user”)註解,會在elasticesearch裡面建立一個user的索引,@Id註解白名uId欄位為elasticsearch的id欄位。
@Document(indexName = "user")public class User implements Serializable { @Id private String uId; private String name; private Integer age; private String address; //省略getter setter }
寫一個介面UserRepository繼承ElasticsearchRepository,ElasticsearchRepository包含了基本的增刪改查的能力,並在介面類上加上@Repository註解,注入到spring 容器中。
@Repositorypublic interface UserRepository extends ElasticsearchRepository<User, String> {}
UserServiceImpl類去操作UserRepository的介面,去操作Elasticsearch。
@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public long count() { return userRepository.count(); } @Override public User save(User user) { return userRepository.save(user); } @Override public void delete(User user) { userRepository.delete(user); } @Override public Iterable<User> getAll() { return userRepository.findAll(); } @Override public List<User> getByName(String name) { List<User> list = new ArrayList<>(); MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name); Iterable<User> iterable = userRepository.search(matchQueryBuilder); iterable.forEach(e->list.add(e)); return list; } @Override public Page<User> pageQuery(Integer pageNo, Integer pageSize, String kw) { NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(QueryBuilders.matchPhraseQuery("name", kw)) .withPageable(PageRequest.of(pageNo, pageSize)) .build(); return userRepository.search(searchQuery); }}
寫一個測試類,然後依次呼叫介面:
@RestControllerpublic class TestController { @Autowired private UserService userService; @GetMapping("/testInsert") public void testInsert() { User user = new User(); user.setuId("1"); user.setName("zhangsna"); user.setAge(101); user.setAddress("廣東省深圳市"); userService.save(user); user.setuId("2"); user.setName("lisi"); user.setAge(32); user.setAddress("廣東省深圳市"); userService.save(user); user.setuId("3"); user.setName("wangwu"); user.setAge(34); user.setAddress("廣東省深圳市"); userService.save(user); } @GetMapping("/testDelete") public void testDelete() { User user = new User(); user.setuId("1"); userService.delete(user); } @GetMapping("/testGetAll") public void testGetAll() { Iterable<User> iterable = userService.getAll(); iterable.forEach(e -> System.out.println(e.toString())); } @GetMapping("/testGetByName") public void testGetByName() { List<User> list = userService.getByName("lisi"); System.out.println(list); } @GetMapping("/testPage") public void testPage() { Page<User> page = userService.pageQuery(0, 10, "wangwu"); System.out.println(page.getTotalPages()); System.out.println(page.getNumber()); System.out.println(page.getContent()); }}
kibana展示資料首先需要按照kibana,安裝命令如下:
wget https://artifacts.elastic.co/downloads/kibana/kibana-7.7.0-x86_64.rpmshasum -a 512 kibana-7.7.0-x86_64.rpm sudo rpm --install kibana-7.7.0-x86_64.rpm//設定kibana開機自啟sudo /bin/systemctl daemon-reloadsudo /bin/systemctl enable kibana.servicesudo systemctl start kibana.service //啟動kibanasudo systemctl stop kibana.service //停止kibana
啟動成功後,在瀏覽器上訪問kibana的地址http://10.10.10.1:5601,進入kibana的主介面。然後進到Discover介面。選擇user的索引,就可以正常展示資料,資料如下: