代码+注释
//增加 /索引/类型/id
PUT /test1/people/1
{
"name": "狂神",
"age": 13,
"interts": ["游泳","游戏","睡觉"]
}
PUT /test1/people/2
{
"name": "小狂神",
"age": 3,
"interts": ["游泳","游戏","吃饭"]
}
PUT /test1/people/3
{
"name": "大狂神",
"age": 23,
"interts": ["篮球","游戏","学习"]
}
//轻量搜索 name = 神
GET /test1/_search?q=name:神
//使用查询表达式搜索,_search搜索不能写type
GET /test1/_search
{
"query": {
"match": {
"age": "3"
}
}
}
GET /test1/_search
{
"query": {
"bool": {
"must": [
{"match": {
"name": "狂神"
}}
],
//添加过滤器
"filter": [
{"range": {
"age": {
//gte:大于等于,lte:小于等于
"gte": 10
}
}}
]
}
}
}
//POST更新不会改变原有的字段,用PUT更新会完全覆盖原来的字段
//更新操作,存在更新的字段
POST /test1/people/3/_update
{
"doc": {
"name": "狂神"
}
}
//更新不存在的字段,相当于直接添加
POST /test1/people/3/_update
{
"doc": {
"about": "I like go to rack climbing"
}
}
POST /test1/people/1/_update
{
"doc": {
"about": "I like to collect rack albums"
}
}
POST /test1/people/3/_update
{
"doc": {
"about": "I love to go rack climbing"
}
}
POST /test1/people/2/_update
{
"doc": {
"about": "I want to be a rich man"
}
}
//查询匹配,会查询到只包含rack或者climbing的数据
GET /test1/_search
{
"query": {
"match": {
"about": "rack climbing"
}
}
}
//查询匹配短语,只会查询到完全包含词短语的数据
GET /test1/_search
{
"query": {
"match_phrase": {
"about": "rack climbing"
}
}
}
GET /test1/_search
{
"query": {
"match_phrase": {
"about": "rack climbing"
}
},
//高亮查询字段about
"highlight": {
"fields": {
"about": {}
}
}
}
//聚合查询,查出索引中所有的interts字段
GET /test1/_search
{
"aggs": {
"all_interests": {
"terms": {
"field": "interts.keyword"
}
}
}
}
//查询interts字段中的平均年龄
GET /test1/_search
{
"query": {
"match": {
"name": "狂神"
}
},
"aggs": {
"all_age": {
"terms": {
"field": "interts.keyword"},
"aggs": {
"avg_age": {
"avg": {"field": "age"}
}
}
}
}
}
GET test1/_search
{
"sort":[
{
"age": {
"order": "desc"//倒序
}
}
],
"from": 0,//相当于mysql分页查询
"size": 1
}
GET /test1/_search
{
"query": {
"match": {
"name": "狂神"
}
},
"_source": ["name","age"]//指定要查询的资源(name和age)
}
//规定属性的类型,相当于mysql的字段类型
//如果规定,test2索引的type相当于默认的_doc,如果添加其它的type则会报错
PUT /test2
{
"mappings": {
"properties": {
"name": {
"type": "text"
},
"age": {
"type": "long"
},
"birthday": {
"type": "date"
}
}
}
}
知识点
查询
term是直接通过倒排索引指定的词条进程精确查找的
关于分词:
- term:精确查询(使用倒排索引)
- match:会使用分词器解析(先分析文档,然后通过分析的文档进行查询)
两种类型(相当于字段):
- keyword:关键词 ,不会被分词器解析(是一个整体)
- text:文本,会被分词器解析
来源于:遇见狂神说,elasticsearch教学视频
视频链接: [狂神说Java]ElasticSearch.