Spring boot2.3.4 + Elasticsearch7.x Java demo Github源码:
https://github.com/Mengzuozhu/es-demo
1. ES查询
接口:
GET /index_name/_search
POST /index_name/_search
全量查询
{}
或
{
"query": {
"match_all": {}
}
}
range
查询
- gt 大于
- gte 大于等于
- lt 小于
- lte 小于等于
{
"query": {
"range": {
"field": {
"gte": 20,
"lt": 30
}
}
}
}
term
精确查询
{
"query": {
"term": {
"field": "value"
}
}
}
terms
多值查询
{
"query": {
"terms": {
"field": ["value1","value2"]
}
}
}
match
全文查询
- 既能处理全文字段,又能处理精确字段
{
"query": {
"match": {
"field": "text"
}
}
}
multi_match
多字段 查询
{
"query": {
"multi_match": {
"query": "text",
"fields": ["field1", "field2"]
}
}
}
match_phrase
短语查询
- 与match的区别是:match_phrase搜索词项(分词后)的
顺序位置
要一致,匹配更严格
{
"query": {
"match_phrase": {
"field": "your text"
}
}
}
query_string
查询
- 与match的区别是:match匹配指定字段;而query_string默认匹配
所有合适字段
,也可指定查询字段(default_field
)
{
"query": {
"query_string": {
"query": "text",
"default_field": "field"
}
}
}
exists
查询和 missing
查询
{
"query": {
"exists": {
"field": "value"
}
}
}
bool
组合多查询
- must:必须都匹配这些条件,与
AND
等价 - must_not:必须不匹配这些条件,与
NOT
等价 - should:至少匹配这些条件中的一个,与
OR
等价 - filter:必须匹配,但它以不评分、过滤模式来进行,支持缓存
{
"query": {
"bool": {
"must": {
"match": {
"field1": "value1"
}
},
"must_not": {
"match": {
"field2": "value2"
}
},
"should": [
{
"match": {
"field3": "value3"
}
},
{
"range": {
"field4": {
"gte": 4
}
}
}
],
"filter": {
"match": {
"field5": "value5"
}
},
}
}
}
nested
嵌套对象查询
{
"query": {
"nested": {
"path": "firstPath",
"query": {
"match": {
"firstPath.field": "text"
}
}
}
}
}
2. 聚合
最大值
聚合
{
"aggs": {
"max_field": { "max": { "field": "your field" } }
}
}
最小值
聚合
{
"aggs": {
"min_field": { "min": { "field": "your field" } }
}
}
均值
聚合
{
"aggs": {
"avg_field": { "avg": { "field": "your field" } }
}
}
Terms
聚合
对应字段值的文档数统计
{
"aggs": {
"terms_count": { "terms": { "field": "your field" } }
}
}
基数(唯一值数目)
聚合
即字段的 distinct 或者 unique 值的数目
{
"aggs": {
"unique_count": {
"cardinality": {
"field": "your field"
}
}
}
}
3. 分析与分析器
测试分析器
GET /_analyze
{
"analyzer": "standard",
"text": "Text to analyze"
}
4. 映射管理
- 查看映射
GET /index_name/_mapping
5. 索引管理
- _cat帮助:
GET /_cat
- 查看所有索引:
GET /_cat/indices?v
- 查看指定索引:
GET /_cat/indices/{index}?v
- 格式化参数(可选):
?v