查询语句:
GET /lib4/user/_search
{"query": {"term": {"interests":"唱歌"}}
}#terms:查询某个字段里含有多个关键词的文档
GET /lib4/user/_search
{"query":{"terms":{"interests": ["喝酒","唱歌"]}}
}
数据准备:
#2.7.1数据准备
PUT /lib4
{ "settings":{"number_of_shards" : 3, "number_of_replicas" :0},"mappings":{"user":{"properties":{"name": {"type":"text","analyzer":"ik_max_word"}, "address": {"type":"text","analyzer": "ik_max_word"},"age": {"type" :"integer"},"interests": {"type":"text","analyzer": "ik_max_word"},"birthday": {"type":"date"}}}}
}
#ik芾有两个分词器
#ik_max_word :会将文本做最细粒度的拆分;尽可能多的拆分出词语
#ik_smart:会做最粗粒度的斥分;已被分出的词语将不会再次被其它词语占有
#2.7.2 term查询和terms查询
#term query会去倒排索引中寻找确切的term,它并不知道分词器的存在。
#这种查询适合keyword、numeric、date.
#term:查询某个字段里含有某个关键词的文档
添加5个文档:
PUT /lib4/user/1
{"name" : "赵六","address" : "黑龙江省 铁岭","age" : 50,"birthday" : "1970-12-12","interests": "喜欢喝酒,锻炼,说相声"
}PUT /lib4/user/2
{"name" :"赵明","address" :"北京海淀区清河","age" : 20,"birthday" : "1998-10-12" ,"interests": "喜欢喝酒,锻炼,唱歌"
}PUT /lib4/user/3
{"name" : "lisi","address" :"北京海淀区清河","age" : 23,"birthday" : "1998-10-12","interests": "喜欢喝酒,锻炼,唱歌"
}PUT /lib4/user/4
{"name" :"王五","address" : " 北京海淀区清河","age" : 26,"birthday" : "1995-10-12","interests": "喜欢编程,听音乐,旅游"
}PUT /lib4/user/5
{"name" : "张三","address" :"北京海淀区清河","age" : 29,"birthday" : "1988-10-12","interests": "喜欢摄影,听音乐,跳舞"
}
term和terms查询
term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇
#term和terms查询
#查询字段中含有赵的
GET /lib4/user/_search
{"query": {"term": {"name":"赵"}}
}#指定多个关键字,只要包含其中一个就会被查询出来
GET /lib4/user/_search
{"query":{"terms":{"interests": ["喝酒","唱歌"]}}
}#控制返回的数据条数 取前2条
GET /lib4/user/_search
{"from":0,"size": 2, "query":{"terms":{"interests": ["喝酒","唱歌"]}}
}#版本号的返回
GET /lib4/user/_search
{"version":true,"query":{"terms":{"interests": [" 喝酒", "唱歌"]}}
}
match查询 match是知道分词器存在的这个之前就讲过
赵六会被分词为两个词 含有赵和六的都会被查询出来
#match查询
GET /lib4/user/_search
{"query":{"match":{"name": "赵六"}}
}
然后对于数字型的是不会被分词的比如查询年龄20的 这个不会被分成2和0 所以查询结果会去从文档匹配年龄为20的信息
GET /lib4/user/_search
{"query":{"match":{"age": 20}}
}GET /lib4/user/_search
{"query": {"match_all": {}}
}
#multi_match指定多个字段关键字匹配 ;match_phrase短语精确匹配 ;_source指定查询结果返回的字段信息
#指定多个字段匹配
GET /lib4/user/_search
{"query":{"multi_match": {"query": "唱歌","fields": ["interests", "name"]}}
}#短语匹配
GET lib4/user/_search
{"query":{"match_phrase" :{"interests": "锻炼,说相声"}}
}#返回指定的字段
GET /lib4/user/_search
{"_source": ["address" , "name"],"query": {"match": {"interests": "唱歌"}}
}