ES的简单使用

ES

1:简单操作

  1. 创建索引

    PUT http://127.0.0.1:9200/shopping
    
  2. 查看所有索引

    GET http://127.0.0.1:9200/_cat/indices?v
    
  3. 查看单个索引

    GET http://127.0.0.1:9200/shopping
    
  4. 删除单个索引

    DELETE http://127.0.0.1:9200/shopping
    
  5. 创建文档数据json

    POST http://127.0.0.1:9200/shopping/_doc
    {
        "title": "小米手机",
        "category": "小米",
        "images": "http://www.gulixueyuan.com/xm.jpg",
        "price": 3999.00
    }
    
  6. 创建文档数据带唯一标识的数据

    POST http://127.0.0.1:9200/shopping/_doc/1
    {
        "title": "华为手机",
        "category": "华为",
        "images": "http://www.gulixueyuan.com/xm.jpg",
        "price": 3999.00
    }
    
  7. 查看单个文档数据, 查看所有文档在下面

    GET http://127.0.0.1:9200/shopping/_doc/1
    
  8. 修改文档

    POST http://127.0.0.1:9200/shopping/_doc
    {
     "title":"华为手机",
     "category":"华为",
     "images":"http://www.gulixueyuan.com/hw.jpg",
     "price":4999.00
    }
    
  9. 修改文档中的单个字段

    POST http://127.0.0.1:9200/shopping/_update/1
    {
         "doc": {
         "price":30.00
     	}
    }
    
  10. 删除文档(逻辑标记删除)

    DELETE http://127.0.0.1:9200/shopping/_doc/1
    
  11. 删除一个不存在的文档

    DELETE http://127.0.0.1:9200/shopping/_doc/1
    
  12. 条件删除文档

    POST http://127.0.0.1:9200/shopping/_delete_by_query
    {
         "query":{
             "match":{
             	"price":4000.00
             }
         }
    }
    
  13. 创建映射_先创建索引再创建映射,类似于数据库(database)中的表结构(table)。 创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型 下有哪些字段,每个字段有哪些约束信息,这就叫做映射(mapping)。

    PUT http://127.0.0.1:9200/s
    
    PUT http://127.0.0.1:9200/s/_mapping
    {
        "properties":{
            "name":{
                "type":"text",
                "index":true
            },
            "sex":{
                "type":"text",
                "index":true
            },
            "age":{
                "type":"long",
                "index":true
            }
        }
    }
    
  14. 查看映射

    GET http://127.0.0.1:9200/s/_mapping
    
  15. 索引映射关联,s1与s进行关联

    PUT http://127.0.0.1:9200/s1
    {
        "settings":{},
        "mappings":{
            "properties":{
                "name":{
                    "type":"text",
                    "index":true
                },
                "sex":{
                    "type":"text",
                    "index":true
                },
                "age":{
                    "type":"long",
                    "index":true
                }
            }
        }
    }
    

2:高级查询

  1. 定义数据

    POST http://127.0.0.1:9200/student/_doc/1001
    {
        "name":"zhangsan",
        "nickname":"zhangsan",
         "sex":"男",
         "age":30
    }
    
    POST http://127.0.0.1:9200/student/_doc/1002
    {
    "name":"lisi",
    "nickname":"lisi",
     "sex":"男",
     "age":20
    }
    
    POST http://127.0.0.1:9200/student/_doc/1003
    {
    "name":"wangwu",
     "nickname":"wangwu",
     "sex":"女",
     "age":40
    }
    
    POST http://127.0.0.1:9200/student/_doc/1004
    {
    "name":"zhangsan1",
    "nickname":"zhangsan1",
     "sex":"女",
     "age":50
    }
    
    POST http://127.0.0.1:9200/student/_doc/1005
    {
    "name":"zhangsan2",
    "nickname":"zhangsan2",
     "sex":"女",
     "age":30
    }
    
  2. 高级查询_查询所有文档
    “query”:这里的 query 代表一个查询对象,里面可以有不同的查询属性
    “match_all”:查询类型,例如:match_all(代表查询所有), match,term , range 等等
    {查询条件}:查询条件会根据类型的不同,写法也有差异

    GET http://127.0.0.1:9200/student/_search
    {
     "query": {
     "match_all": {}
    }
    
  3. 高级查询,match 匹配类型查询

    GET http://127.0.0.1:9200/student/_search
    // match 匹配类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是 or 的关系
    {
        "query":{
            "match":{
                "name":"zhangsan1"
            }
        }
    }
    
    
  4. 高级查询,multi_match字段匹配查询

    GET http://127.0.0.1:9200/student/_search
    // multi_match 与 match 类似,不同的是它可以在多个字段中查询
    {
        "query":{
            "multi_match":{
                "query":"zhangsan",
                "fields":[
                    "name",
                    "nickname"
                ]
            }
        }
    }
    
  5. 高级查询,term关键字精确查询

    GET http://127.0.0.1:9200/student/_search
    // term 查询,精确的关键词匹配查询,不对查询条件进行分词。
    {
        "query":{
            "term":{
                "name":{
                    "value":"zhangsan"
                }
            }
        }
    }
    
  6. 高级查询,terms多关键字精确查询

    GET http://127.0.0.1:9200/student/_search
    // terms 查询和 term 查询一样,但它允许你指定多值进行匹配。
    // 如果这个字段包含了指定值中的任何一个值,那么这个文档满足条件,类似于 mysql 的 in
    {
        "query":{
            "terms":{
                "name":[
                    "zhangsan",
                    "lisi"
                ]
            }
        }
    }
    
  7. 高级查询,_source指定具体的查询字段

    GET http://127.0.0.1:9200/student/_search
    // 默认情况下,Elasticsearch 在搜索的结果中,会把文档中保存在_source 的所有字段都返回。
    // 如果我们只想获取其中的部分字段,我们可以添加_source 的过滤
    {
        "_source":[
            "name"//,"nickname","sex"
        ],
        "query":{
            "terms":{
                "nickname":[
                    "zhangsan"
                ]
            }
        }
    }
    
  8. 高级查询,includes过滤字段,包含某一个字段

    GET http://127.0.0.1:9200/student/_search
    // includes:来指定想要显示的字段
    // excludes:来指定不想要显示的字段
    {
        "_source":{
            "includes":[
                "name",
                "nickname"
                //,"sex"
            ]
        },
        "query":{
            "terms":{
                "nickname":[
                    "zhangsan"
                ]
            }
        }
    }
    
  9. 高级查询,excludes过滤字段,排除某一个字段

    GET http://127.0.0.1:9200/student/_search
    {
        "_source":{
            "excludes":[
                "name",
                "nickname"
            ]
        },
        "query":{
            "terms":{
                "nickname":[
                    "zhangsan"
                ]
            }
        }
    }
    
  10. 高级查询,bool_must组合查询

    GET http://127.0.0.1:9200/student/_search
    // `bool`把各种其它查询通过`must`(必须 )、`must_not`(必须不)、`should`(应该)的方 式进行组合
    {
        "query":{
            "bool":{
                "must":[
                    {
                        "match":{
                            "name":"zhangsan"
                        }
                    }
                ]
            }
        }
    }
    
  11. 高级查询,bool_must_not组合查询

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "bool":{
                "must_not":[
                    {
                        "match":{
                            "age":"40"
                        }
                    }
                ]
            }
        }
    }
    
  12. 高级查询,bool_should组合查询

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "bool":{
                "should":[
                    {
                        "match":{
                            "sex":"男"
                        }
                    }
                ]
            }
        }
    }
    
  13. 高级查询,range范围查询

    gt 大于>

    gte 大于等于>=

    lt 小于<

    lte 小于等于<=

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "range":{
                "age":{
                    "gte":30,
                    "lte":35
                }
            }
        }
    }
    
  14. 模糊查询,fuzzy 查询会在指定的编辑距离内创建一组搜索词的所有可能的变体 或扩展。然后查询返回每个扩展的完全匹配

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "fuzzy":{
                "title":{
                    "value":"zhangsan"
                }
            }
        } 
    }
    
  15. 高级查询_单字段排序,sort 可以对不同的字段进行排序,通过 order 指定排序的方式:desc 降序,asc 升序

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "match":{
                "name":"zhangsan"
            }
        },
        "sort":[
            {
                "age":{
                    "order":"desc"
                }
            }
        ]
    }
    
  16. 高级查询_高亮展示 在使用
    match 查询的同时,加上一个 highlight 属性:
    pre_tags:前置标签
    post_tags:后置标签
    fields:需要高亮的字段
    title:这里声明 title 字段需要高亮,后面可以为这个字段设置特有配置,也可以空

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "match":{
                "name":"zhangsan"
            }
        },
        "highlight":{
            "pre_tags":"<font color='red'>",
            "post_tags":"</font>",
            "fields":{
                "name":{
    
                }
            }
        }
    }
    
  17. 高级查询_分页查询

    from:当前页的起始索引,默认从 0 开始。 from = (pageNum - 1) * size
    size:每页显示多少条

    GET http://127.0.0.1:9200/student/_search
    {
        "query":{
            "match_all":{
    
            }
        },
        "sort":[
            {
                "age":{
                    "order":"desc"
                }
            }
        ],
        "from":0,
        "size":2
    }
    
  18. 高级查询_聚合查询__最大值max

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "max_age":{
                "max":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  19. 高级查询_聚合查询__最小值min

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "min_age":{
                "min":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  20. 高级查询_聚合查询__对某个字段求和 sum

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "sum_age":{
                "sum":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  21. 对某个字段取平均值 avg

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "avg_age":{
                "avg":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  22. 对某个字段的值进行去重之后再取总数

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "distinct_age":{
                "cardinality":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  23. Stats 聚合,对某个字段一次性返回 count,max,min,avg 和 sum 五个指标

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "stats_age":{
                "stats":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  24. 桶聚合查询

    桶聚和相当于 sql 中的 group by 语句 terms 聚合,分组统计,在 terms 分组下再进行聚合

    GET http://127.0.0.1:9200/student/_search
    // terms 聚合,分组统计
    {
        "aggs":{
            "age_groupby":{
                "terms":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    
  25. 桶聚合查询
    在 terms 分组下再进行聚合

    GET http://127.0.0.1:9200/student/_search
    {
        "aggs":{
            "age_groupby":{
                "terms":{
                    "field":"age"
                }
            }
        },
        "size":0
    }
    

3:Java API 操作

  1. 创建 Maven 项目

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.8.0</version>
    </dependency>
    <!-- elasticsearch 的客户端 -->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.8.0</version>
    </dependency>
    <!-- elasticsearch 依赖 2.x 的 log4j -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.9</version>
    </dependency>
    <!-- junit 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
  2. 创建索引

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    // 创建索引
    CreateIndexRequest request = new CreateIndexRequest("user");
    CreateIndexResponse createIndexResponse = client.indices().create( request, RequestOptions.DEFAULT );
    // 获取响应
    boolean acknowledged = createIndexResponse.isAcknowledged();
    System.out.println("索引操作-----"+acknowledged);
    // 关闭客户端
    client.close();
    
  3. 获取索引

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    GetIndexRequest request = new GetIndexRequest("user");
    GetIndexResponse response = client.indices().get(request,RequestOptions.DEFAULT);
    System.out.println("aliases:"+response.getAliases());
    System.out.println("mappings:"+response.getMappings());
    System.out.println("settings:"+response.getSettings());
    client.close();
    
  4. 删除索引

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    // 请求对象
    DeleteIndexRequest request = new DeleteIndexRequest("user");
    // 发送请求,获取响应
    AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
    // 获取响应结果
    System.out.println(response.isAcknowledged());
    // 关闭客户端
    client.close();
    
  5. 添加文档数据

    // 文档数据对象
    @Data
    public class EsUser {
        private String name;
        private Integer age;
        private String sex;
    }
    
    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    IndexRequest request = new IndexRequest();
    request.index( "user" ).id("1");
    EsUser esUser = new EsUser();
    esUser.setAge( 10 );
    esUser.setName( "zhangsan" );
    esUser.setSex( "男" );
    ObjectMapper mappers = new ObjectMapper();
    String value = mappers.writeValueAsString( esUser );
    request.source( value,XContentType.JSON );
    IndexResponse index = client.index( request, RequestOptions.DEFAULT );
    System.out.println(index.getResult());
    client.close();
    
  6. 批量添加文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    BulkRequest request = new BulkRequest();
    IndexRequest indexRequest = new IndexRequest();
    indexRequest.index( "user" ).id( "2" ).source( XContentType.JSON,"name","张三" );
    IndexRequest indexRequest1 = new IndexRequest();
    indexRequest1.index( "user" ).id( "3" ).source( XContentType.JSON,"name","李四" );
    IndexRequest indexRequest2 = new IndexRequest();
    indexRequest2.index( "user" ).id( "4" ).source( XContentType.JSON,"name","王五" );
    request.add( indexRequest );
    request.add( indexRequest1 );
    request.add( indexRequest2 );
    BulkResponse responses = client.bulk( request, RequestOptions.DEFAULT );
    System.out.println("took:" + responses.getTook());
    System.out.println("items:" + responses.getItems());
    client.close();
    
  7. 更新文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    UpdateRequest request = new UpdateRequest();
    request.index( "user" ).id( "1" );
    request.doc( XContentType.JSON,"sex","女" );
    UpdateResponse update = client.update( request, RequestOptions.DEFAULT );
    System.out.println("result----"+update.getResult());
    System.out.println("index----"+update.getIndex());
    System.out.println("id----"+update.getId());
    client.close();
    
  8. 获取单个文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    GetRequest request = new GetRequest().index( "user" ).id( "1" );
    GetResponse response = client.get( request, RequestOptions.DEFAULT );
    System.out.println("_index:" + response.getIndex());
    System.out.println("_type:" + response.getType());
    System.out.println("_id:" + response.getId());
    System.out.println("source:" + response.getSourceAsString());
    client.close();
    
  9. 删除文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    DeleteRequest request = new DeleteRequest().index( "user" ).id( "1" );
    DeleteResponse response = client.delete( request, RequestOptions.DEFAULT );
    System.out.println(response.toString());
    System.out.println("_index:" + response.getIndex());
    System.out.println("_id:" + response.getId());
    client.close();
    
  10. 批量删除文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    BulkRequest request = new BulkRequest();
    DeleteRequest request1 = new DeleteRequest().index( "user" ).id( "2" );
    DeleteRequest request2 = new DeleteRequest().index( "user" ).id( "3" );
    DeleteRequest request3 = new DeleteRequest().index( "user" ).id( "4" );
    request.add( request1 );
    request.add( request2 );
    request.add( request3 );
    BulkResponse responses = client.bulk( request, RequestOptions.DEFAULT );
    System.out.println("took:" + responses.getTook());
    System.out.println("items:" + responses.getItems());
    client.close();
    
  11. 高级查询_获取索引中的所有文档数据

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    // 创建搜索请求对象
    SearchRequest request = new SearchRequest();
    // user 指定索引
    request.indices("student");
    // 创建查询请求体
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 查询所有
    sourceBuilder.query( QueryBuilders.matchAllQuery() );
    request.source( sourceBuilder );
    // 发送请求
    SearchResponse response = client.search( request, RequestOptions.DEFAULT );
    // 获取响应结果
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    // 输出每条查询的结果信息
    for (SearchHit hit : hits) {
    	System.out.println(hit.getSourceAsString());
    }
    client.close();
    
  12. 高级查询_term精确查询

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    SearchRequest request = new SearchRequest();
    request.indices( "student" );
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(QueryBuilders.termQuery( "name","zhangsan" ) );
    request.source( sourceBuilder );
    SearchResponse response = client.search( request, RequestOptions.DEFAULT );
    SearchHits hits = response.getHits();
    // 获取响应结果
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    for (SearchHit hit : hits){
    	System.out.println(hit.getSourceAsString());
    }
    client.close();
    
  13. 高级查询_分页查询

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    SearchRequest request = new SearchRequest();
    request.indices( "student" );
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query( QueryBuilders.matchAllQuery() );
    sourceBuilder.from( 0 );
    sourceBuilder.size( 3 );
    request.source( sourceBuilder );
    SearchResponse response = client.search( request, RequestOptions.DEFAULT );
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    for (SearchHit hit : hits){
    	System.out.println(hit.getSourceAsString());
    }
    client.close();
    
  14. 高级查询_sort排序

    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );
    SearchRequest request = new SearchRequest();
    request.indices( "student" );
    SearchSourceBuilder sourceBuilder= new SearchSourceBuilder();
    sourceBuilder.query( QueryBuilders.matchAllQuery() );
    sourceBuilder.sort( "age",SortOrder.ASC );
    request.source( sourceBuilder );
    SearchResponse response = client.search( request, RequestOptions.DEFAULT );
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    for (SearchHit hit : hits){
    	System.out.println(hit.getSourceAsString());
    }
    client.close();
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值