Elasticsearch也是基于Lucene的全文检索库,本质也是存储数据,很多概念与MySQ类似,对比:
索引(indices)----Databases 数据库
类型(type)--------Table 数据表
文档(Document)-Row 行
字段(Field)--------Columns 列
详细说明:
概念 | 说明 |
---|---|
索引库(indices) | indices是index的复数,代表许多的索引, |
类型(type) | 类型是模拟mysql中的table概念,一个索引库下可以有不同类型的索引,比如商品索引,订单索引,其数据格式不同。不过这会导致索引库混乱,因此未来版本中会移除这个概念 |
文档(document) | 存入索引库原始的数据。比如每一条商品信息,就是一个文档 |
字段(field) | 文档中的属性 |
映射配置(mappings) | 字段的数据类型、属性、是否索引、是否存储等特性 |
请求方式:PUT
请求路径:/索引库名
请求参数:json格式:
PUT /heima
{
"settings": {//索引库的设置
"number_of_shards": 3,//分片数量
"number_of_replicas": 2//副本数量
}
}
查看索引:用GET heima查看是否建立好数据库
删除索引:DELETE /索引库名
语法:
PUT /索引库名/_mapping/类型名称
{
"properties": {
"字段名": {
"type": "类型",
"index": true,
"store": true,
"analyzer": "分词器"
}
}
}
例子:
PUT heima/_mapping/goods
{
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"images": {
"type": "keyword",
"index": "false"
},
"price": {
"type": "float"
}
}
}
查看映射关系(查看数据库字段建好了没有):
语法:GET /索引库名/_mapping
示例:GET /commodity/_mapping
语法:
POST /索引库名/类型名
{
"key":"value"
}
示例:
POST /heima/goods/ //后边加1代表自定义id不加数字是随机产生id 例子:POST /heima/goods/1
{
"title":"小米手机",
"images":"http://image.leyou.com/12479122.jpg",
"price":2699.00,
"saleable":true
}
注:字段少的可以直接通过新增数据添加
通过kibana查看数据:
查看结果:
DELETE /heima/goods/1(通过kibana查看数据得知id是1)
基本查询:
GET /索引库名/_search
{
"query":{
"查询类型":{
"查询条件":"查询条件值"
}
}
}
查询类型:
- 例如:match_all, match,term , range 等等
例:
查询所有:
GET /heima/_search
{
"query":{
"match_all":{}
}
}
GET /heima/_search
{
"query": {
"multi_match":{
"query":"小米",
"fields": ["title","subTitle"]
}
}
}
多词条查询:
terms 查询和 term 查询一样,但它允许你指定多值进行匹配。如果这个字段包含了指定值中的任何一个值,那么满足条件:
GET /heima/_search
{
"query":{
"terms": {
"title": [
"值",
"值"
]
}
}
}
GET /heima/_search
{
"_source": {
"includes":["title","price"] //查询结果包括title和price字段
},
"query": {
"term": {
"price": 2699
}
}
}
range查询找出那些落在指定区间内的数字或时间
GET /heima/_search
{
"query":{
"range": {
"price": {
"gte": 1000.0,
"lt": 2800.00
}
}
}
}
range允许查询一下字符:
gt:大于 gte:大于等于 lt:小于 lte:小于等于
GET /heima/_search
{
"query": {
"fuzzy": {
"title": {
"value":"appla",
"fuzziness":1 //最大为2
}
}
}
}
所有的查询都会影响到文档的评分及排名,如果我们不影响评分排名就要使用filter
GET /heima/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手机" }},
"filter":{
"range":{"price":{"gt":2000.00,"lt":3800.00}}
}
}
}
"sort": [ //排序
{ "price": { "order": "desc" }},//如果价格相同 根据_id排序
{ "_id": { "order": "desc" }}
]
}
无条件:
用constant_score取代bool查询
GET /heima/_search
{
"query":{
"constant_score": {
"filter": {
"range":{"price":{"gt":2000.00,"lt":3000.00}}
}
}
}