In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "the process explanation of spring boot2 integrating ES". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
One: running environment
JDK:1.8
ES:5.6.4
Second: learning content
How to build a spring-data-elasticsearch environment?
How to achieve common additions, deletions, modifications and queries?
How to achieve the one-to-many relationship of object nesting?
Third: JAVA depends on the environment
According to the official website of spring-data-elasticsearch, I use the 3.0.6.RELEASE version and spring boot uses 2.0.1.RELEASE.
4.0.0 org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE com.huize.pluto.els demo 1.0.0-SNAPSHOT jar demo http://maven.apache.org UTF-8 5.6.4 1.8 Spring-libs-milestone https://repo.spring.io/libs-milestone spring-plugins-release https://repo.spring.io/plugins-release Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.data Spring-data-elasticsearch 3.0.6.RELEASE org.elasticsearch elasticsearch ${elasticsearch.version} Org.elasticsearch.client transport ${elasticsearch.version} commons-logging commons-logging Org.apache.maven.plugins maven-compiler-plugin 3.5.1 1.8 1.8 1.8 UTF-8 4. Spring-data-elasticsearch details 4.1: configuring ES
Declare ElasticsearchTemplate bean; (of course, you can also use the spring boot auto-configuration method, because later you have to directly use JAVA API to operate ES, so this is configured in code)
/ * configure ES to support cluster * / @ Configurationpublic class ElasticConfigration {@ Value ("${elasticsearch.host}") private String esHost; @ Value ("${elasticsearch.port}") private int esPort; @ Value ("${elasticsearch.clusterName}") private String esClusterName; private TransportClient client @ PostConstruct public void initialize () throws Exception {Settings esSettings = Settings.builder () .put ("cluster.name", esClusterName) .put ("client.transport.sniff", true) .build (); client = new PreBuiltTransportClient (esSettings); String [] esHosts = esHost.trim () .split (",") For (String host: esHosts) {client.addTransportAddress (new InetSocketTransportAddress (InetAddress.getByName (host), esPort);}} @ Bean public Client client () {return client;} @ Bean public ElasticsearchTemplate elasticsearchTemplate () throws Exception {return new ElasticsearchTemplate (client) } @ PreDestroy public void destroy () {if (client! = null) {client.close ();} 4.2: write entity classes
Declare each field type and its corresponding properties:
Declare a USER entity and note that there is an one-to-many roles * * / @ Document (indexName = "test-user", type= "user", replicas=0,shards=3) public class User {@ Id private String id; @ Field (type=FieldType.keyword) private String userName; @ Field (type=FieldType.Integer) private Integer age; @ Field (type=FieldType.Date) private Date birthday / * declare that the participle is ik_smart (note that es needs to install the ik participle plug-in) * / @ Field (searchAnalyzer= "ik_smart", analyzer= "ik_smart", type=FieldType.text) private String description; / * 1-to-many in spring-data-elasticsearch is unified as nested type * / @ Field (type=FieldType.Nested,includeInParent=true) private List roles Public User () {} public User (String userName,Integer age,Date birthday,String description) {this.userName = userName; this.age = age; this.birthday = birthday; this.description = description;} public String getId () {return id;} public void setId (String id) {this.id = id } public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public Date getBirthday () {return birthday;} public void setBirthday (Date birthday) {this.birthday = birthday;} public Integer getAge () {return age } public void setAge (Integer age) {this.age = age;} public String getDescription () {return description;} public void setDescription (String description) {this.description = description;} public List getRoles () {return roles;} public void setRoles (List roles) {this.roles = roles } @ Document (indexName = "test-role", type= "role", replicas=0,shards=3) public class Role {@ Id private String id; @ Field (type=FieldType.keyword) private String name; @ Field (type=FieldType.Date) private Date createTime; @ Field (searchAnalyzer= "ik_smart", analyzer= "ik_smart", type=FieldType.text) private String description Public Role () {} public Role (String name,String description,Date createTime) {this.name = name; this.description = description; this.createTime = createTime;} public String getId () {return id;} public void setId (String id) {this.id = id;} public String getName () {return name } public void setName (String name) {this.name = name;} public Date getCreateTime () {return createTime;} public void setCreateTime (Date createTime) {this.createTime = createTime;} public String getDescription () {return description;} public void setDescription (String description) {this.description = description }} 4.3: write dao
As long as you inherit ElasticsearchRepository, you can add, delete, subtract and search functions commonly used, and you can add some other queries that you need.
Public interface UserRepository extends ElasticsearchRepository {/ / query List findByUserNameLike (String userName) by userName like; / / query List findByRolesName (String name) by name attribute of role; / / query List findByRoles_Name (String name) by name attribute of role;} 4.4: write service@Servicepublic class UserStandardService implements StandardService {@ Autowired private UserRepository userRepository; @ Autowired private ElasticsearchTemplate elasticsearchTemplate / * batch added * * / @ Override public void batchAddUser (List users) {if (CollectionUtils.isEmpty (users)) {return;} List queries = Lists.newArrayListWithExpectedSize (users.size ()); IndexQuery indexItem = null; for (User user: users) {indexItem = new IndexQuery () IndexItem.setObject (user); queries.add (indexItem);} elasticsearchTemplate.bulkIndex (queries);} @ Override public void addUser (User user) {userRepository.save (user);} @ Override public void deletedUserById (String id) {userRepository.deleteById (id) } / * Update information according to userId * / @ Override public void updateUser (User user) {UpdateQuery updateQuery = new UpdateQuery (); updateQuery.setId (user.getId ()); updateQuery.setClazz (User.class); user.setId (null); UpdateRequest request = new UpdateRequest (); request.doc (JsonUtils.beanToJson (user)) UpdateQuery.setUpdateRequest (request); elasticsearchTemplate.update (updateQuery);} @ Override public List queryByUserName (String userName) {return userRepository.findByUserNameLike (userName);} @ Override public List queryByRoleName (Role role) {return userRepository.findByRoles_Name (role.getName ());}} 4.5: launch
The main thing is to add @ EnableElasticsearchRepositories annotation.
@ EnableElasticsearchRepositories (basePackages = "com.test.els.demo.core.user.repository") @ SpringBootApplicationpublic class DemoApplication {private static final Logger logger = LoggerFactory.getLogger (DemoApplication.class); public static void main (String [] args) {SpringApplication.run (DemoApplication.class, args); logger.info ("start completed!") ;}}
OK, this is the end of spring-data-elasticsearch practice.
This is the end of the introduction of "the process of spring boot2 integrating ES". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.