先准备好数据
PUT /nba
put /nba/_mapping
{
"properties": {
"name": {
"type": "text"
},
"team_name": {
"type": "text"
},
"position": {
"type": "text"
},
"play_year": {
"type": "long"
},
"jerse_no": {
"type": "keyword"
}
}
}
put nba/_doc/1
{
"name": "哈登",
"team_name": "火箭",
"position": "得分后卫",
"play_year": 10,
"jerse_no": "13"
}
put nba/_doc/2
{
"name": "库里",
"team_name": "勇士",
"position": "控球后卫",
"play_year": 10,
"jerse_no": "30"
}
put nba/_doc/3
{
"name": "詹姆斯",
"team_name": "湖人",
"position": "小前锋",
"play_year": 15,
"jerse_no": "23"
}
term(词条)查询和full text(全文)查询
词条查询:词条查询不会分析查询条件,只有当词条和查询字符串完全匹配时,才匹配搜索。
全文查询:ElasticSearch引擎会先分析查询字符串,将其拆分成多个分词,只要已分析的字段中包含词条的任意一个,或全部包含,就匹配查询条件,返回该文档;如果不包含任意一个分词,表示没有任何文档匹配查询条件
个人总结
term查询,字段的类型为keyword或其它
全文查询,字段的类型一定要是text,可以分词,否则没意义
单条term查询
post /nba/_search
{
"query": {
"term": {
"jerse_no": "23"
}
}
}
多条term查询
post /nba/_search
{
"query": {
"terms": {
"jerse_no": [
"23",
"13"
]
}
}
}
match_all,测试结果 返回所有,from,size可以分页
post /nba/_search
{
"query": {
"match_all": {}
},
"from": 0,
"size": 10
}
match,测试结果返回 id为1和2的记录
post /nba/_search
{
"query": {
"match": {
"position": "后卫"
}
},
"from": 0,
"size": 10
}
POST /nba/_update/2
{
"doc": {
"name": "库⾥",
"team_name": "勇⼠",
"position": "控球后卫",
"play_year": 10,
"jerse_no": "30",
"title": "the best shooter"
}
}
multi_match 多字段搜索
multi_match多字段匹配的三种类型,分别是best_fields(最佳字段) 、 most_fields(多数字段) 和 cross_fields(跨字段)
best_fields类型,multi_match默认的查询类型,可以省略不写
post /nba/_search
{
"query": {
"multi_match": {
"query": "卫",
"fields": [
"position"
],
"type": "best_fields"
}
},
"from": 0,
"size": 10
}
match_pharse
post /nba/_search
{
"query": {
"match_phrase": {
"position": "后卫"
}
},
"from": 0,
"size": 10
}
match_phrase_prefix
post /nba/_search
{
"query": {
"match_phrase_prefix": {
"position": "小"
}
},
"from": 0,
"size": 10
}