基础查询

POST http://127.0.0.1:9200/book/_search

  • 1.简单查询
{
	"query":{
		"match_all":{}
	}
}
  • 2.条件查询
{
	"query":{
		"match":{
			"title":"入门到精通"
		}
	},
	"from":1,
	"size":5,
	"sort":{
		"publish_date":{
			"order":"asc"
		}
	}
	
}
  • 3.聚合查询
{
	"aggs":{
		"group_by_word_count":{
			"terms":{
				"field":"word_count"
			}
		},
		"group_by_publish_date":{
			"terms":{
				"field":"publish_date"
			}
		}
	}
	
}
{
	"aggs":{
		"total_word_count":{
			"stats":{
				"field":"word_count"
			}
		}
	}
}
{
	"aggs":{
		"max_word_count":{
			"max":{
				"field":"word_count"
			}
		}
	}
}

高级查询

1.子条件查询 又称叶子条件查询(特定字段查询所指特定的值)

  • 1.1Query Context 在查询的过程中,除了判断文档是否满足查询条件外,ES还会计算一个_score来标识匹配的程度,旨在判断目标文档和查询条件的匹配程度有多好。
1.1.1全文本查询:针对文本类型(text)的数据
  • --1.模糊匹配
{
	"query":{
		"match":{
			"title":"PHP从入门到精通"
		}
	}
}

会匹配PHP、从入门到精通两个关键词

  • --2.习语匹配
{
	"query":{
		"match_phrase":{
			"title":"PHP从入门到精通"
		}
	}
}
  • --3.多个字段模糊匹配查询
{
	"query":{
		"multi_match":{
			"query":"PHP",
			"fields":["title","author"]
		}
	}
}

查询title或author中包含PHP关键字

  • --4.1语法查询
{
	"query":{
		"query_string":{
			"query":"(PHP AND 入门) OR 普改"
		}
	}
}

文本字段同时包含PHP和入门两个关键词或者文本字段包含普改

  • --4.2查询多字段(指定字段查询)
{
	"query":{
		"query_string":{
			"query":"PHP",
			"fields":["title","author"]
		}
	}
}
  • 1.1.2字段级别查询:针对结构化数据,如数字、日期等
  • --1.指定字段精确查询
{
	"query":{
		"term":{
			"author":"普改"
		}
	}
}
  • --2.范围查询
  • --2.1数字范围
{
	"query":{
		"range":{
			"word_count":{
				"gte":"170000",
				"lte":"200000"
			}
		}
	}
}
  • --2.2日期范围
{
	"query":{
		"range":{
			"publish_date":{
				"gte":"2018-01-01",
				"lte":"2019-12-30"
			}
		}
	}
}
{
	"query":{
		"range":{
			"publish_date":{
				"gte":"2019-01-01",
				"lte":"now"
			}
		}
	}
}

1.2Filter Context 在查询过程中,只判断该文档是否满足条件,只有yes或者no. (query判断yes或者no,还会_score匹配程度)

ES会对查询结果做缓存,故速度比Query要快

{
	"query":{
		"bool":{
			"filter":{
				"term":{
					"author":"普改"
				}
				
			}
		}
	}
}

2.复合条件查询(以一定的逻辑组合子查询查询)

{
	"query":{
		"bool":{
			"must":{
				"match":{
					"title":"PHP从入门到精通"
				}
			},
			"filter":{
				"range":{
					"word_count":{
						"gt":170000
					}
				}
			}
			
		}
	},
	"from":1,
	"size":1
}