In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you what is the difference between springboot and elasticsearch, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Core jar:
Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-elasticsearch net.java.dev.jna jna 3.0.9
Why do you use this version? because this is the case with the es version related to springboot. In order to reduce the occurrence of incomprehensible errors later, it is best to keep the es version consistent with the es jar version. Let's not talk about how to create the specific project here. As usual, we first create the physical layer, dao, web:
No configuration is required. Default cluster name elasticsearch, address localhost:9300
Data@Document (indexName= "person", type= "student", shards=5,replicas=1,refreshInterval= "- 1") public class Student implements Serializable {@ Id private Long id; private String name; private String classNo; private int age; private String sex; @ JsonFormat (pattern = "yyyy-MM-dd") private Date birthday; private String grade; private String description;}
Dao:
@ Repositorypublic interface StudentRepository extends ElasticsearchRepository {}
Web:
@ RestController@RequestMapping ("/ student") public class StudentController {@ Autowired private StudentRepository studentRepository; @ GetMapping ("/ {id}") public Student get (@ PathVariable ("id") Long id) {Optional opt = studentRepository.findById (id); return opt.orElseGet (null);} @ GetMapping public Iterable getAll () {return studentRepository.findAll ();} @ PostMapping public Student save (Student student) {return studentRepository.save (student) } @ DeleteMapping ("/ {id}") public void delete (@ PathVariable ("id") Long id) {studentRepository.deleteById (id);}}
It's that simple. Of course, this is not the case, as the main database or query, according to the previous brief introduction to es, we can know that there are many kinds of es query, how to quickly query the ideal data, the key is to be familiar with the use of api.
Now lower the version to test.
Springboot 1.5.21 elasticsearch-5.6.16
Core jar of dependency:
1.8 5.6.16 org.springframework.boot spring-boot-starter-web org.elasticsearch.client transport ${elasticsearch.version} org.elasticsearch.client elasticsearch-rest-high-level-client ${elasticsearch.version} org.elasticsearch elasticsearch ${elasticsearch.version} com.sun.jna jna 3.0.9
First of all, we need to know that there are two kinds of clients to connect to es, one is based on transport, and the other is rest. Let's see how to implement it first (by default, transport port 9300 is rest 9200, which can be modified in es. If it is a cluster environment and it is the same machine, you need to configure each node address)
Transport client:
@ Bean public TransportClient client () throws UnknownHostException {Settings settings = Settings.builder () .put ("cluster.name", properties.getClusterName ()) .build (); List nodes = properties.getNodes (); List addresses = new ArrayList (); for (String node: nodes) {String [] addr = node.split (":") TransportAddress address = new InetSocketTransportAddress (InetAddress.getByName (addr [0]), Integer.valueOf (addr [1])); addresses.add (address);} TransportClient client = new PreBuiltTransportClient (settings) .addTransportAddresses (addresses.toArray (new TransportAddress [addresses.size ()])); return client;}
The rest is how to call the TransportClient to create the index:
Private CreateIndexRequestBuilder configIndex (String index) {if (StringUtils.isEmpty (index)) {log.warn ("index name can't be empty"); return null;} Map config = new HashMap (); if (properties.getProperties ()! = null) {config.putAll (properties.getProperties ()) } Settings settings = Settings.builder () .put (config) .build (); return client.admin () .indices () .prepareCreate (index.toLowerCase ()) .setSettings (settings);} public void createIndex (String index,String type,XContentBuilder source) {CreateIndexRequestBuilder indexBuilder = configIndex (index) If {/ / indexBuilder.setSettings () if (! StringUtils.isEmpty (type)) {indexBuilder.addMapping (type, source);} CreateIndexResponse response = indexBuilder.execute () .actionGet (); boolean ack = response.isAcknowledged () If (ack) {log.info ("index [{}] create successfully!", index);} else {log.warn ("index [{}] create unsuccessfully!", index);}
You don't need type and document attributes to create an index, but of course, if you need to create an index or type, remember to build a full json, like this:
{"settings": {"number_of_shards": 5, "number_of_replicas": 1}, "mappings": {"type1": {"properties": {"prop1": {"type": "text"...}. }}. }}
Delete the index:
Public boolean deleteIndex (String... Index) {return client.admin (). Indices (). PrepareDelete (index). Execute (). ActionGet (). IsAcknowledged ();}
Save the document:
Public void saveDoc (String index, String type,String id, String source) {if (StringUtils.isEmpty (id)) {log.warn ("id is empty,and generate id automatically."); id = UUID.randomUUID (). ToString ();} IndexResponse response = client.prepareIndex (index, type, id) .setSource (source,XContentType.JSON). Get () Log.debug ("save date status: [{}]", response.status () .getStatus ();}
Modify the document:
Public void updateDoc (String index, String type, String id,String source) {UpdateResponse response = client.prepareUpdate (index, type, id) .setDoc (source,XContentType.JSON). Get (); log.debug ("update date status: [{}]", response.status (). GetStatus ());}
Delete the document:
Public void deleteDoc (String index, String type, String id) {client.prepareDelete (index,type,id). Execute (). ActionGet ();}
Query:
Public List query (String index, String type,QueryBuilder query) {SearchRequestBuilder builder = client.prepareSearch (); if (! StringUtils.isEmpty (index)) {builder.setIndices (index);} if (! StringUtils.isEmpty (type)) {builder.setTypes (type);} SearchResponse response = builder.setQuery (query). Get (); SearchHits hits = response.getHits () / / long total = hits.totalHits; Iterator hitIt = hits.iterator (); List result = new ArrayList (); while (hitIt.hasNext ()) {SearchHit hit = hitIt.next (); result.add (hit.getSourceAsMap ());} return result;}
Rest client:
@ Bean public RestClient client () {List nodes = properties.getNodes (); List hosts = null; if (nodescrafts null) {hosts = nodes.stream () .map (e-> {/ / match? String [] addr = e.split (":"); return new HttpHost (addr [0], Integer.valueOf (addr [1]));} RestClientBuilder restClientBuilder; if (Collectors.toList ());} RestClientBuilder restClientBuilder; if (hosts! = null) {restClientBuilder = RestClient.builder (hosts.toArray (new HttpHost [hosts.size ()])) } else {log.warn ("no host is configured,user default {}: {}", DEFAULT_HOST,DEFAULT_PORT); restClientBuilder = RestClient.builder (new HttpHost (DEFAULT_HOST,DEFAULT_PORT));} / / httpConfigure (restClientBuilder); return restClientBuilder.build ();}
This is the same as the native es call, and of course there is an asynchronous method.
Client.performRequest (String method, String url, Map params, HttpEntity entity, HttpAsyncResponseConsumerFactory consumerFactory)
The key is to build HttpEntiy, because es mainly communicates through data in json format, so the key is how to build data in json format for transmission. Of course, we can use some json tools to do this:
Public static String builder () {Map json = new HashMap (); Map match_all = new HashMap (); match_all.put ("match_all", Collections.EMPTY_MAP); json.put ("query", match_all); try {return new ObjectMapper () .writeValueAsString (json) } catch (JsonProcessingException e) {e.printStackTrace ();} return null;} these are the differences between springboot and elasticsearch. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.