下载安装
windows安装
下载对应平台版本
下载地址:https://www.elastic.co/jp/downloads/elasticsearch
启动
es安装目录下的/bin/elasticsearch.bat
./bin/elasticsearch.bat
访问
localhost:9200
常见问题
本地访问不了
找到./config/elasticsearch.yml文件,将xpack.security.enabled由true改为false
# Enable security features
xpack.security.enabled: false
其他问题看日志文件
./logs/elasticsearch.log
索引类型
正排索引
id查找内容,模糊需要全表扫描
倒排索引
关键字绑定id,再根据id查内容
基础操作(postman)
创建索引
创建一个名为shopping的索引
put请求: localhost:9200/shopping
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "shopping"
}
get请求查看索引,delete请求删除索引
创建文档
es自动生成id
在索引为shopping中添加一条数据
post请求:localhost:9200/shopping/_doc
{
"phone": "红米",
"price": "1999.00"
}
es指定id
在索引为shopping中添加一条数据并指定id为1
post请求:localhost:9200/shopping/_doc/1
{
"phone": "红米",
"price": "1999.00"
}
查询文档
#查询id为1的文档
get请求:ost:9200/shopping/_doc/1
#全部查询
get请求:ost:9200/shopping/_search
更新文档
#更新文档id为1数据(数据全部更新)
put请求:localhost:9200/shopping/_doc/1
{
"phone": "红米",
"price": "1999.00",
"status": "0"
}
#更新文档id为1数据(部分更新)
post请求:localhost:9200/shopping/_update/1
{
"doc":{
"status": "1"
}
}
删除
#删除文档id为1数据
put请求:localhost:9200/shopping/_doc/1
搜索文档
#url中带参数搜索
get请求:localhost:9200/shopping/_search?q=phone:小米
#请求体搜索(推荐)
get请求:localhost:9200/shopping/_search
{
"query":{
"match": {
"phone": "小米"
}
}
}
分页查询
get请求:localhost:9200/shopping/_search
{
"query":{
"match_all": {
}
},
"from": 0,
"size": "1"
}
排序
get请求:localhost:9200/shopping/_search
#_source为需要显示的字段名称, sort排序字段
{
"query":{
"match_all": {
}
},
"from": 0,
"size": 1,
"_source":["phone"],
"sort": {
"price.keyword": {
"order": "desc"
}
}
}
问题:No mapping found for [keyword] in order to sort on
解决方法1
用.keyword进行聚合
"sort": {
"price.keyword": {
"order": "desc"
}
}
解决方法2
设置price这个排序字段的fileddata为true。
PUT请求:localhost:9200/shopping/_mapping
{
"properties": {
"price":{
"type": "text",
"fielddata": true
}
}
}
多条件查询
get请求:localhost:9200/shopping/_search
//与查询 查询品牌为小米状态为1的手机
{
"query":{
"bool": {
"must": [{
"match": {
"phone":"小米"
}
},
{
"match": {
"status":"0"
}
}
]
}
}
}
get请求:localhost:9200/shopping/_search
//或查询 查询品牌为小米或华为的手机
{
"query":{
"bool": {
"should": [{
"match": {
"phone":"小米"
}
},
{
"match": {
"status":"0"
}
}
]
}
}
}
范围查询
get请求:localhost:9200/shopping/_search
{
"query":{
"bool": {
"must": [{
"match": {
"phone":"小米"
}
},
{
"match": {
"status":"0"
}
}
],
"filter": {
"range": {
"price": {
"lt": 2000,
"gt": 1000
}
}
}
}
}
}
精确匹配
get请求:localhost:9200/shopping/_search
{
"query":{
"match_phrase": {
"phone": "红米"
}
}
}
高亮显示
#category 高亮这字段
{
"query":{
"match":{
"phone" : "红米"
}
},
"highlight":{
"fields":{
"phone":{}
}
}
}