您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關springboot與elasticsearch有什么區(qū)別,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
核心jar:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>3.0.9</version> </dependency>
為什么用這樣的版本,因為springboot相關的es版本就是這樣,為了減少之后無法理解的錯誤出現,最好將es版本與es jar的版本保持一致,具體項目怎么創(chuàng)建這里就不說了,像平時一樣,我們首先創(chuàng)建實體層、dao、web:
不需要任何配置,默認集群名稱elasticsearch,地址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:
@Repository public interface StudentRepository extends ElasticsearchRepository<Student,Long> { }
web:
@RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentRepository studentRepository; @GetMapping("/{id}") public Student get(@PathVariable("id") Long id){ Optional<Student> opt = studentRepository.findById(id); return opt.orElseGet(null); } @GetMapping public Iterable<Student> 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); } }
就是這樣簡單。當然是用并非如此,作為數據庫主要的還是查詢,根據上一篇對es的簡單介紹,可以 知道es的查詢有很多種,如何快速查詢出理想的數據,關鍵還是對api的使用與熟悉。
現在降低一下版本來測試
springboot 1.5.21 elasticsearch-5.6.16
依賴的核心jar:
<properties> <java.version>1.8</java.version> <elasticsearch.version>5.6.16</elasticsearch.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--transport client--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>${elasticsearch.version}</version> </dependency> <!--rest client--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>com.sun.jna</groupId> <artifactId>jna</artifactId> <version>3.0.9</version> </dependency> </dependencies>
首先要知道,連接es有兩種客戶端,一種是基于transport,一種是rest,我們分別看先如何實現(默認情況下transport端口9300,rest 9200,在es中可以修改,如果是集群環(huán)境,且為同一機器,需要配置各個節(jié)點地址)
Transport客戶端:
@Bean public TransportClient client() throws UnknownHostException { Settings settings = Settings.builder() .put("cluster.name",properties.getClusterName()) .build(); List<String> nodes = properties.getNodes(); List<TransportAddress> 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; }
其余就是如何調用這個TransportClient,創(chuàng)建index:
private CreateIndexRequestBuilder configIndex(String index){ if(StringUtils.isEmpty(index)){ log.warn("index name can't be empty"); return null; } Map<String,Object> 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!=null){ // 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); } } }
創(chuàng)建索引可以不需要type和document屬性,當然,如果需要創(chuàng)建index、type,記得構建的是一個完整的json,類似這樣:
{ "settings":{ "number_of_shards":5, "number_of_replicas":1 }, "mappings":{ "type1":{ "properties":{ "prop1":{"type":"text"...} ..... } } ..... } }
刪除索引:
public boolean deleteIndex(String... index) { return client.admin().indices().prepareDelete(index).execute().actionGet().isAcknowledged(); }
保存文檔:
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()); }
修改文檔:
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()); }
刪除文檔:
public void deleteDoc(String index, String type, String id){ client.prepareDelete(index,type,id).execute().actionGet(); }
查詢:
public List<Map<String, Object>> 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<SearchHit> hitIt = hits.iterator(); List<Map<String,Object>> result = new ArrayList<>(); while (hitIt.hasNext()){ SearchHit hit = hitIt.next(); result.add(hit.getSourceAsMap()); } return result; }
Rest客戶端:
@Bean public RestClient client(){ List<String> nodes = properties.getNodes(); List<HttpHost> hosts = null; if(nodes!=null){ hosts = nodes.stream().map(e -> { // match? String[] addr = e.split(":"); return new HttpHost(addr[0], Integer.valueOf(addr[1])); }).collect(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(); }
這個和es原生的調用一樣,當然還有一個異步的方法
client.performRequest(String method, String url, Map<String, String> params, HttpEntity entity, HttpAsyncResponseConsumerFactory consumerFactory);
關鍵是構建HttpEntiy,因為es主要是通過json格式的數據進行通信,所以關鍵就是如何構建json格式的數據進行傳遞,當然我們可以借助一些json工具來完成:
public static String builder(){ Map<String,Object> json = new HashMap<>(); Map<String,Object> 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; }
以上就是springboot與elasticsearch有什么區(qū)別,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。