ElasticSearch学习笔记(六)查询

Open 这个 分享 由 lemontea 发布于 2017-10-26 · 882 阅读 0 回复
lemontea 评论于 2017-10-26

ElasticSearch查询可以有下面几种方式:

  • 简单查询
  • 条件查询
  • 聚合查询

一共准备了6条数据用来测试(测试数据所以拼凑的可能与实际有出入):

{
    "title": "花开堪折",
    "author": "雪域倾情",
    "word_count": 63336,
    "publish_date": "2004-02-15"
}
{
    "title": "九鼎记",
    "author": "我吃西红柿",
    "word_count": 2077131,
    "publish_date": "2015-03-11"
}
{
    "title": "飞剑问道",
    "author": "我吃西红柿",
    "word_count": 10000,
    "publish_date": "2017-09-21"
}
{
    "title": "绝世唐门",
    "author": "唐家三少",
    "word_count": 5071000,
    "publish_date": "2012-12-21"
}
{
    "title": "神墓",
    "author": "辰东",
    "word_count": 3002416,
    "publish_date": "2007-09-27"
}
{
    "title": "一念永恒",
    "author": "耳根",
    "word_count": 2876300,
    "publish_date": "2014-04-27"
}

1、使用id精确查询数据,url为:

http://localhost:9200/book/novel/1

GET查询后返回正确结果:

{
    "_index": "book",
    "_type": "novel",
    "_id": "1",
    "_version": 2,
    "found": true,
    "_source": {
        "title": "花开堪折",
        "author": "雪域倾情",
        "word_count": 63336,
        "publish_date": "2004-02-15"
    }
}

2、使用title匹配查询,url:

http://localhost:9200/book/novel/_search

POST方式请求报文:

{
  "query": {
    "match": {
      "title": "一念"
    }
  }
}

返回正确结果:

{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1.8913201,
        "hits": [
            {
                "_index": "book",
                "_type": "novel",
                "_id": "6",
                "_score": 1.8913201,
                "_source": {
                    "title": "一念永恒",
                    "author": "耳根",
                    "word_count": 2876300,
                    "publish_date": "2014-04-27"
                }
            }
        ]
    }
}

3、按publish_date排序

{
  "query": {
    "match": {
      "title": "一念"
    }
  },
  "sort": [
      {"publish_date": {"order": "desc"}}
  ]
}

4、聚合查询,请求地址没有变,只是json内容变了

{
    "aggs": {
        "group_by_word_count": {
            "terms": {
                "field": "word_count"
            }
        },
        "group_by_publish_date": {
            "terms": {
                "field": "publish_date"
            }
        }
    }
}

5、聚合查询,统计

{
    "aggs": {
        "group_by_word_count": {
            "stats": {
                "field": "word_count"
            }
        }
    }
}

返回结果,由于篇幅有限,这里只贴部分响应内容:

"aggregations": {
        "group_by_word_count": {
            "count": 6,
            "min": 10000,
            "max": 5071000,
            "avg": 2183363.8333333335,
            "sum": 13100183
        }
    }