因为最近换了公司,公司主要的数据存储用的是ES,所以学习一下ES的知识。本次是开篇,讲下基础操作;
# ES基础操作
### TIP
如果请求不通或者pedding状态,可能的问题为ES过滤了跨域名请求;
解决办法:修改 [elasticsearch安装目录]/config/elasticsearch.yml 文件
```
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.enabled 配置项表示是否支持跨域,默认为false;
http.cors.allow-origin,当设置允许跨域,默认为*,表示支持所有域名,如果我们只是允许某些网站能访问,那么可以使用正则表达式;
没有这两项可以创建,修改完后重启即可;
```
使用的版本 5.2.0
### CURD
1、ip:port 后面三段分别为 索引、类型、ID;
2、ID为可选字段,不带ID时ES会自己生成一个字符串的ID
3、put/post两种方式都可以成功;
4、更新会时会更新字段和版本号+1;
一、创建、更新
```
PUT/POST http://127.0.0.1:9200/movies/movie/6
入参
{
"title": "霸王别姬",
"director": "陈凯歌",
"year": 1993,
"genres": []
}
创建返回:
{
"_index": "movies",
"_type": "movie",
"_id": "6",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
更新返回:
{
"_index": "movies",
"_type": "movie",
"_id": "6",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": false
}
```
二、删除
和创建、更新的URL相同,http方法改为DELETE
```
DELETE http://127.0.0.1:9200/movies/movie/6
# 删除返回
{
"found": true,
"_index": "movies",
"_type": "movie",
"_id": "6",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
```
三、查询(DSL)
1、使用http POST方法
2、url中添加_search,可以对全局、索引、类型搜素;
3、URL中添加**,**可以同时搜索多个索引;
```
http://127.0.0.1:9200/_search //全局
http://127.0.0.1:9200/movies,schools/_search //索引
http://127.0.0.1:9200/movies/movie/_search //类型
```
在5.0之后已经不支持最后说的过滤器查询了,查询后提示no [query] registered for [filtered]
#### 查询示例
```
POST http://127.0.0.1:9200/_search
{
"query": {
"query_string": {
"query": "ford",
"fields": ["title"]
}
}
}
返回
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.89014244,
"hits": [
{
"_index": "movies",
"_type": "movie",
"_id": "12",
"_score": 0.89014244,
"_source": {
"title": "The Assassination of Jesse James by the Coward Robert Ford",
"director": "Andrew Dominik",
"year": 2007,
"genres": [
"Biography",
"Crime",
"Drama"
]
}
}
]
}
}
```
网友评论