Elasticsearch_3. 代码命令_基础入门

作者: 小疯子 分类: Elasticsearch 发布时间: 2019-05-18 12:49

 

#创建文档
PUT /customer/_doc/2
{
  "name": "Lisi",
  "age": 2
}
PUT /customer/_doc/3
{
  "name": "Wang wu",
  "age": 12
}
PUT /customer/_doc/4
{
  "name": "Wang liu",
  "age": 13
}
#检索文档
GET /customer/_doc/1

#查看所有索引信息
GET /_cat/indices?v&pretty

#获取所有索引名下的文档
GET /_search

#轻量搜索:获取customer索引名下的文档
GET /customer/_search

#轻量搜索:搜索名字为Lisi的用户
GET /customer/_search?q=name:Lisi

#使用查询表达式搜索,实现复杂的搜索,以下命令搜索名字为Lisi的用户
GET /customer/_search
{
  "query" : {
    "match" : {
      "name" : "Lisi"
    }
  }
}

#更复杂的搜索,既搜索名字为Lisi的会员,而且只需要年龄大于1的。查询需要稍作调整,使用过滤器
GET /customer/_search
{
  "query": {
    "bool":{
      "must": {
        "match":{
          "name":"Lisi"
        }
      },
      "filter":{
        "range":{
          "age":{"gt":1}
        }
      }
    }
  }
}

#全文搜索,除了查到Wang wu名字的用户之外,其他带Wang和wu文字的用户也会显示,在全文属性上搜索并返回相关性最强的结果。相关性得分通过_score展示出来
GET /customer/_search
{
  "query" : {
    "match" : {
      "name" : "Wang wu"
    }
  }
}

#短语搜索,比如上面要搜索名字为Wang wu这一短语的用户
GET /customer/_search
{
  "query" : {
    "match_phrase" : {
      "name" : "Wang wu"
    }
  }
}

#高亮搜索,新增一个highlight参数即可
GET /customer/_search
{
  "query" : {
    "match_phrase" : {
      "name" : "Wang wu"
    }
  },
  "highlight": {
    "fields": {
      "name" : {}
    }
  }
}

#增加测试文档
PUT /employee/_doc/1
{
    "first_name" : "John",
    "last_name" :  "Smith",
    "age" :        25,
    "about" :      "I love to go rock climbing",
    "interests": [ "sports", "music" ]
}
PUT /employee/_doc/2
{
    "first_name" :  "Jane",
    "last_name" :   "Smith",
    "age" :         32,
    "about" :       "I like to collect rock albums",
    "interests":  [ "music" ]
}
PUT /employee/_doc/2
{
    "first_name" :  "Douglas",
    "last_name" :   "Fir",
    "age" :         35,
    "about":        "I like to build cabinets",
    "interests":  [ "forestry" ]
}

GET /employee/_search

# 分析:属于Elasticsearch的聚合功能,与SQL中的GROUP BY类似但更强大:挖掘用户年龄和用户数的匹配
GET /customer/_search
{
  "aggs":{
    "ages":{
      "terms": {
        "field": "age"
      }
    }
  }
}

#分析:可以先搜索再聚合,搜索Wang wu全文搜索结果后
GET /customer/_search
{
  "query" : {
    "match" : {
      "name" : "Wang wu"
    }
  },
  "aggs":{
    "ages":{
      "terms": {
        "field": "age"
      }
    }
  }
}

#error: 分析:还支持分级汇总,查询特定兴趣爱好员工的平均年龄
GET /employee/_search
{
    "aggs" : {
        "all_interests" : {
            "terms" : { "field" : "interests" },
            "aggs" : {
                "avg_age" : {
                    "avg" : { "field" : "age" }
                }
            }
        }
    }
}

 

0

发表评论

电子邮件地址不会被公开。 必填项已用*标注