本篇文章给大家分享的是有关springboot与elasticsearch有什么区别,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
创新互联专注于固阳网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供固阳营销型网站建设,固阳网站制作、固阳网页设计、固阳网站官网定制、微信小程序开发服务,打造固阳网络公司原创品牌,更为您提供固阳网站排名全网营销落地服务。
核心jar:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-elasticsearch net.java.dev.jna jna 3.0.9
为什么用这样的版本,因为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{ }
web:
@RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentRepository studentRepository; @GetMapping("/{id}") public Student get(@PathVariable("id") Long id){ Optionalopt = 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); } }
就是这样简单。当然是用并非如此,作为数据库主要的还是查询,根据上一篇对es的简单介绍,可以 知道es的查询有很多种,如何快速查询出理想的数据,关键还是对api的使用与熟悉。
现在降低一下版本来测试
springboot 1.5.21 elasticsearch-5.6.16
依赖的核心jar:
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
首先要知道,连接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(); Listnodes = 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; }
其余就是如何调用这个TransportClient,创建index:
private CreateIndexRequestBuilder configIndex(String index){ if(StringUtils.isEmpty(index)){ log.warn("index name can't be empty"); return null; } Mapconfig = 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
Rest客户端:
@Bean public RestClient client(){ Listnodes = properties.getNodes(); List 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, Mapparams, HttpEntity entity, HttpAsyncResponseConsumerFactory consumerFactory);
关键是构建HttpEntiy,因为es主要是通过json格式的数据进行通信,所以关键就是如何构建json格式的数据进行传递,当然我们可以借助一些json工具来完成:
public static String builder(){ Mapjson = 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; }
以上就是springboot与elasticsearch有什么区别,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。