您好,登录后才能下订单哦!
本篇文章给大家分享的是有关springboot与elasticsearch有什么区别,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
核心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的版本保持一致,具体项目怎么创建这里就不说了,像平时一样,我们首先创建实体层、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中可以修改,如果是集群环境,且为同一机器,需要配置各个节点地址)
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,创建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); } } }
创建索引可以不需要type和document属性,当然,如果需要创建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有什么区别,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。