这里通过POSTMAN建表
先在虚拟机上启动数据库
一般在bin/目录中
1、./elasticsearch
2、npm run start
建表
PUT http://192.168.56.99:9200/[数据库名]/_mapping/[表名]
在Body => raw中操作,将Text改成Json
{
"settings":{
"index":{
"number_of_shards": 3, //分片数量为3
"number_of_replicas": 1 //副本数量为1
}
},
"mappings":{
"teststore":{
"properties":{ //映射参数
"name":{"type":"keyword"},
"age":{"type":"integer"},
"birthday":{
"type":"date",
"format":"yyyy-MM-dd||epoch_millis"
}
}
}
}
}
这里建了三个映射参数
name,age,birthday
往表中添加信息
{
"name":"zhangsan"
"age":"30"
"birthday":"1995-06-07"
}
修改表
PUT http://192.168.56.99:9200/[数据库名]/_mapping/[表名]
{
"properties":{
"hobby":{"type":"text"} //这里添加映射参数hobby,类型为text
}
}
添加信息
POST http://192.168.56.99:9200/[数据库名]/_mapping/[表名]
{
"name":"aa",
"age":12,
"birthday":"1923-12-21",
"hobby":"play games, watch films"
}
查询
GET http://192.168.56.99:9200/[数据库名]/[表名]/_search
查询所有
{
"query":{
"match_all":{}
}
}
单个查询
{
"query": {
"match": {
"name": {
"query": "zhangsan"
}
}
}
}
短语查询
{
"query": {
"match_phrase": {
"hobby": "play games"
}
}
}
聚合查询
{
"aggs":{
"avg_age":{
"avg":{
"field":"age"
}
},
"sum_age":{
"sum":{
"field":"age"
}
}
}
}
根据名字分桶
{
"size": 0,
"aggs":{
"mybulk":{
"terms":{
"field":"name"
}
}
}
}
多字段匹配查询
{
"query" : {
"multi_match" : {
"query" : "cooking"
"fields" : ["hobbys","skills"] //从多个参数中查找
}
}
}
terms多词条查询
{
"query":{
"terms":{
"hobby":["watch","play"]
}
}
}
range范围查询
{
"query":{
"range":{
"custid":{
"gte":15000, //大于等于15000,小于等于20000
"lte":20000 //如果不想等于,去掉e
}
}
}
}
bool布尔查询
{
"query": {
"bool": {
"filter": [
{
"match": {"name": "zhangsan"}
},
{
"match": {"age": "30"}
}
]
}
},
"size":3, //每页条数
"from":1 //从第几行开始
}
区别
查询关键字 | 区别 |
---|---|
match | 短语、单词都能查出来 |
match_phrase | 能查单词和连接型短语 |
term | 只能查单词 |
terms | 多词条查询 |
过滤类型 | 区别 |
---|---|
filter | 必须满足每一个条件,不参与计算分值 |
must | 必须满足每一个条件,参与计算分值 |
should | 满足其中一个条件即可 |
must_not | 每个条件都不满足 |
补充
开启fielddata
作用:进行聚合操作
PUT http://192.168.56.99:9200/[数据库名]/_mapping/[表名]
{
"properties":{
"browser":{ //要开启的参数名
"type":"text",//类型
"fielddata":true
}
}
}