一.es环境的搭建
安装jdk1.8es官网下载es.tar.gz 解压运行es bin/elasticsearch (如何linux为32位启动会报错,但是不影响正常使用)
二.es分词器下载
在github搜索 elasticsearch-ik选择对应版本的ik下载编译好ik,别下source code(源码 需要编译)将下载好的ik 解压到 plugins 下的ik 文件夹重启es查看 curl -XPOST localhost:9200/_analyze?pretty -d ‘{“analyzer”:“ik_smart”, “text”:“我是一个中国人”}’
三.es常用命令
curl 命令参数意义 -X 指定http的请求方法 HEAD GET POST PUT DELETE -d 指定要传输的数据 -H 指定http请求头信息 参数详情可以使用 curl --help查看各参数的含义 (以上参数是严格区分大小写的 )
es 结构 index (索引对应为库) type(类型对应为表) document(文档对应一条记录)
es新增语句 curl -XPUT localhost:9200/abc(索引)/employee(类型)/1(文档id) -d ‘{“name”:“张三”,“age”:30}’ curl -XPOST localhost:9200/abc(索引)/employee(类型)/2(文档id) -d ‘{“name”:“李四”,“age”:30}’
es查询 curl -XGET localhost:9200/abc/employee/1?pretty (根据id) curl -XGET localhost:9200/abc/employee/_search (查询type下的 所有) curl -XGET localhost:9200/abc/_search (查询index下的所有)
es删除 curl -XDELETE localhost:9200/abc/employee/1 curl -XDELETE localhost:9200/abc/employee curl -XDELETE localhost:9200/abc
es更新 curl -XPOST localhost:9200/abc/employee/2 -d ‘{“age”:“35”,“name”:“李四2”}’ (整体更新) curl -XPOST localhost:9200/abc/employee/2 -d ‘{“doc”:{“age”:33}}’ (局部更新)
四.java集成es简单案例
配置elasticsearch.yml network.host: 192.168.1.106 transport.tcp.port: 9300 http:port: 9200 满足实现网络接口的访问引入es pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置properties文件
server.port=8888
spring.data.elasticsearch.cluster-nodes=192.168.1.106:9300
java表关系映射 及 dao层的初始化 (1)创建实体类对应 类型(type)
package com.abc.elasticsearchdemo.entity;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "testgoods",type = "goods")
public class GoodsInfo {
private Long id;
private String name;
private String description;
public GoodsInfo(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public GoodsInfo(Long id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public GoodsInfo( ) {
}
}
(2)配置ElasticRepository bean
package com.abc.elasticsearchdemo.dao;
import com.abc.elasticsearchdemo.entity.GoodsInfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> {
}
(3)测试
@RestController
public class GoodsController {
@Autowired
private GoodsRepository goodsRepository;
@RequestMapping("/save")
public String save(){
GoodsInfo goodsInfo=new GoodsInfo(System.currentTimeMillis()
,"商品"+System.currentTimeMillis(),"这是一个商品");
goodsRepository.save(goodsInfo);
return "success";
}
}