美文网首页技术收藏-开发篇
ElasticSearch常用查询语法

ElasticSearch常用查询语法

作者: 千淘萬漉 | 来源:发表于2019-12-08 22:50 被阅读0次

    以下常用ES常用查询语法整理自:【Elasticsearch检索分类深入详解—基础篇】,墙裂推荐

    1、单个精确查找:

    {
        "query": {
            "term": {
                "price": 20
            }
        }
    }
    

    2、使用过滤器(filters)。过滤器很重要,因为它们执行速度非常快,不会计算相关度(直接跳过了整个评分阶段)而且很容易被缓存。如下: 使用 constant_score 查询以非评分模式来执行 term 查询并以一作为统一评分。

    {
        "query": {
            "constant_score": {
                "filter": {
                    "term": {
                        "price": 20
                    }
                }
            }
        }
    }
    

    5.xES中,对于字符串类型,要进行精确值匹配。需要把类型设置为text和keyword两种类型,JAVA API则如下:

    searchSourceBuilder.query(QueryBuilders.termQuery(“text.keyword”, “来自新华社的报道”));
    

    3.布尔查询

    {
        "bool": {
            "must": [],
            "should": [],
            "must_not": [],
            "filter": []
        }
    }
    

    综合检索场景如下:
    title中包含”Search”且content中包含 “Elasticsearch”,status中精确匹配”published”,并且publish_date 大于“2015-01-01”的全部信息。

    {
        "query": {
            "bool": {
                "must": [{
                        "match": {
                            "title": "Search"
                        }
                    },
                    {
                        "match": {
                            "content": "Elasticsearch"
                        }
                    }
                ],
                "filter": [{
                        "term": {
                            "status": "published"
                        }
                    },
                    {
                        "range": {
                            "publish_date": {
                                "gte": "2015-01-01"
                            }
                        }
                    }
                ]
            }
        }
    }
    

    多个精确值:

    {
        "terms": {
            "price": [20, 30]
        }
    }
    

    4.范围检索(range query)

    • gt: > 大于(greater than)
    • lt: < 小于(less than)
    • gte: >= 大于或等于(greater than or equal to)
    • lte: <= 小于或等于(less than or equal to

    ES中对应的DSL如下:

    {
        "query": {
            "constant_score": {
                "filter": {
                    "range": {
                        "price": {
                            "gte": 20,
                            "lt": 40
                        }
                    }
                }
            }
        }
    }
    

    5. 存在与否检索(exist query)

    ES中,exist查询某个字段是否存在:

    {
        "query" : {
            "constant_score" : {
                "filter" : {
                    "exists" : { "field" : "tags" }
                }
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:ElasticSearch常用查询语法

        本文链接:https://www.haomeiwen.com/subject/yrdugctx.html