今天在使用ElasticSearch查询DSL过滤的时候,使用Sense创建了6个索引,如下
PUT http://localhost:9200/movies/movie/1
{
"title": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"genres": ["Crime", "Drama"]
}
PUT http://localhost:9200/movies/movie/2
{
"title": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"genres": ["Crime", "Drama"]
}
PUT http://localhost:9200/movies/movie/3
{
"title": "To Kill a Mockingbird",
"director": "Robert Mulligan",
"year": 1962,
"genres": ["Crime", "Drama","Mystery"]
}
PUT http://localhost:9200/movies/movie/4
{
"title": "Apocalypse Now",
"director": "Francis Ford Coppola",
"year": 1979,
"genres": ["Drama","War"]
}
PUT http://localhost:9200/movies/movie/5
{
"title": "Kill Bill: Vol. 1",
"director": "Quentin Tarantino",
"year": 2003,
"genres": ["Action", "Crime","Thriller"]
}
PUT http://localhost:9200/movies/movie/6
{
"title": "The Assassination of Jesse James by the Coward Robert Ford",
"director": "Andrew Dominik",
"year": 2007,
"genres": ["Biography","Crime", "Drama"]
}
使用POST http://localhost:9200/movies/_search查询所有索引为movies的文档
查询结果没问题,接下来加入查询条件,查询包含“drama”的文档
POST http://localhost:9200/_search
{
"query": {
"query_string": {
"query": "drama"
}
}
}
结果查到了5条,也没问题,然后再加查询条件,year为2007
POST http://localhost:9200/_search
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "drama"
}
},
"filter": {
"term": {
"year": 2007 }
}
}
}
}
结果出乎意料的报错:no [query] registered for [filtered]
{
"error": {
"root_cause": [
{
"type": "parsing_exception",
"reason": "no [query] registered for [filtered]",
"line": 3,
"col": 21
}
],
"type": "parsing_exception",
"reason": "no [query] registered for [filtered]",
"line": 3,
"col": 21
},
"status": 400
}
百度了一下,发现是因为过滤查询被弃用了,并在ES 5.0中删除,而我的ES版本正是5.2.0
接下来重点来了,用bool实现上面的条件查询(以下方式为本人自己尝试出来的,如有问题,请高调指出),直接上代码
POST http://localhost:9200/_search
{
"query": {
"bool": {
"should": [
{
"query_string": {
"query": "drama"
}
}
],
"must": [
{
"term": {
"year":2007
}
}
]
}
}
}
注意:上面代码中的"[ ]"是我用Sense工具自动生成的,可以去掉,让代码看起来稍微简洁一点点,代码如下
POST http://localhost:9200/_search
{
"query": {
"bool": {
"should":
{
"query_string": {
"query": "drama"
}
},
"must":
{
"term": {
"year": 2007
}
}
}
}
}
最终查询结果有1条数据:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 10,
"successful": 10,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1.1108563,
"hits": [
{
"_index": "movies",
"_type": "movie",
"_id": "6",
"_score": 1.1108563,
"_source": {
"title": "The Assassination of Jesse James by the Coward Robert Ford",
"director": "Andrew Dominik",
"year": 2007,
"genres": [
"Biography",
"Crime",
"Drama"
]
}
}
]
}
}
不要害怕出错,要多尝试不同属性的用法,答案就离自己不远了