本文所有代码在文章最后

本文所有代码在文章最后

创建doc文档

如何连接请看上一篇文章

https://blog.csdn.net/u013979493/article/details/123122242?spm=1001.2014.3001.5502

User user = new User("10002", "lisi", 20, "男");
IndexResponse indexResponse = client.index(
              x -> x.index("user").id(user.getId()).document(user));

修改doc自定义属性

User user = new User();
//修改什么属性就set什么值
user.setAge(101);
UpdateResponse<User> userUpdateResponse = client.update(
                     x -> x.index("user").id("10002").doc(user), User.class);

获取doc信息

GetResponse<User> getResponse = client.get(x -> x
	.index("user")
	.id("10002")
, User.class);

删除doc

client.delete(x -> x.index("user").id("10002"));

批量添加doc

//创建user列表
List<User> users = new ArrayList<>();
users.add(new User("15", "张三", 10, "女"));
users.add(new User("16", "张四", 10, "女"));
users.add(new User("17", "张五六", 11, "女"));
users.add(new User("18", "张三四", 12, "女"));
users.add(new User("19", "张三五", 13, "女"));
users.add(new User("20", "张三六七", 14, "女"));
users.add(new User("21", "张三1", 15, "女"));
//创建BulkOperation列表准备批量插入doc
List<BulkOperation> bulkOperations = new ArrayList<>();
//将user中id作为es id,也可不指定id es会自动生成id
users.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(a.getId()).document(a)))));
client.bulk(x ->x.index("user").operations(bulkOperations));

批量删除doc

List<String> strings = new ArrayList<>();
strings.add("1");
strings.add("2");
strings.add("3");
strings.add("4");
strings.add("5");
strings.add("6");
strings.add("7");
List<BulkOperation> bulkOperations = new ArrayList<>();
strings.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.delete(c -> c.id(a)))));
client.bulk(x ->x.index("user").operations(bulkOperations));

批量更新doc

与添加删除同理

查询user索引所有数据

SearchResponse<User> searchResponse = client.search(a -> a.index("user"), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

条件查询 查询age为15的数据

earchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .term(c -> c
                                            .field("age")
                                            .value(d -> d
                                                    .longValue(15)
                                            )
                                    )
                            ), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

分页查询 排序 过滤字段

SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            //从第0条到第4条
                            .from(0)
                            .size(5)
                            //按年龄降序排序
                            .sort(b -> b
                                    .field(c -> c
                                            .field("age")
                                            .order(SortOrder.Desc)
                                    )
                            )
                            .source(c -> c
                                    .filter(d -> d
                                            //不包含字段
                                            .excludes("id", "age")
                                            //包含字段
                                            .includes("name")
                                    )
                            ), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

组合查询

SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .bool(c -> c
                                    		//必须不满足某些条件
                                            .mustNot(d -> d.match(e -> e.field("sex").query(f -> f.stringValue("男"))))
                                            //可同时满足某些条件
                                            .should(d -> d.match(e -> e.field("age").query(f -> f.longValue(10))))
                                            .should(d -> d.match(e -> e.field("age").query(f -> f.longValue(12))))
                                    )
                            ), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

范围查询

from to查询

SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .range(c -> c.field("age").from("10").to("12"))
                            ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

大于小于查询

SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    //小于等于
//                                    .range(c -> c.field("age").lte(JsonData.of("13")))
                                    //小于
//                                    .range(c -> c.field("age").lt(JsonData.of("13")))
                                    //大于等于
//                                    .range(c -> c.field("age").gte(JsonData.of("13")))
                                    //大于
//                                    .range(c -> c.field("age").gt(JsonData.of("13")))
                                    //范围
                                    .range(c -> c.field("age").from("10").to("13"))

                            )
                            .sort(b -> b.field(c -> c.field("age").order(SortOrder.Asc)))
                            //经测试,若不指定size则只会返回前十条数据,此处这是size是想返回所有数据,如有更好的方法清指教
                            .size(1000), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

模糊查询 高亮显示

SearchResponse<User> searchResponse = client.search(_0 -> _0
                    .query(_1 -> _1
                            .fuzzy(_2 -> _2
                                    .field("name")
                                    //最大偏移量,意为最多有能有几个不符合的
                                    .fuzziness("1")
                                    //最大查询数量
//                                    .maxExpansions(5)
                                    .value(_3 -> _3
                                            .stringValue("张四")
                                    )
                            )
                    )
                    //高亮
                    .highlight(_4 -> _4
                            .fields("name", _5 -> _5
                                    .preTags("<font color='red'>")
                                    .postTags("</font>")
                            )
                    ), User.class);
searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));

聚合操作

SearchResponse<Map> search = client
                    .search(_0 -> _0
                    		//按年龄进行分组
                            .aggregations("ageGroup", _1 -> _1
                                    .terms(_2 -> _2
                                            .field("age")
                                    )
                            ), Map.class);
System.out.println(search);

本文所有方法本人以测试正常使用,如有错误请指正,一起讨论
以下为本文所有代码

User实体类

public class User {
    private String id;
    private String name;
    private int age;
    private String sex;

    public User() {
    }

    public User(String id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

es操作

public class ESClientDemo {

    private static final String clusterNodes = "127.0.0.1:9201";

    private static final String account = "elastic";

    private static final String passWord = "D4ibOD8mtcItd_p_FGUO";

    public static ElasticsearchClient client;

    public static RestClientBuilder builder;

    public static RestClient restClient;

    public static ElasticsearchTransport transport;

    //有密码登录
    public static void main(String[] args) {
        try {
            HttpHost[] httpHosts = Arrays.stream(clusterNodes.split(",")).map(x -> {
                String[] hostInfo = x.split(":");
                return new HttpHost(hostInfo[0], Integer.parseInt(hostInfo[1]));
            }).toArray(HttpHost[]::new);

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            //设置账号密码
            credentialsProvider.setCredentials(
                    AuthScope.ANY, new UsernamePasswordCredentials(account, passWord));

            builder = RestClient.builder(httpHosts)
                    .setHttpClientConfigCallback(httpClientBuilder ->
                            httpClientBuilder
                                    .setDefaultCredentialsProvider(credentialsProvider));

            // Create the low-level client
            restClient = builder.build();
            // Create the transport with a Jackson mapper
            transport = new RestClientTransport(
                    restClient, new JacksonJsonpMapper());
            // And create the API client
            client = new ElasticsearchClient(transport);

//            Boolean acknowledged = client.indices().create(c -> c.index("user")).acknowledged();
//            System.out.println("创建索引: " + (Boolean.TRUE.equals(acknowledged) ? "成功" : "失败"));
//            GetIndexResponse getIndexResponse = client.indices().get(c -> c.index("user"));
//            System.out.println("获取索引 user 响应: " + getIndexResponse);
//            DeleteIndexResponse deleteIndexResponse = client.indices().delete(c -> c.index("user"));
//            System.out.println("删除索引 user 响应: " + deleteIndexResponse);

            //创建doc
//            User user = new User("lisi", 20, "男");
//            IndexResponse indexResponse = client.index(
//                            x -> x.index("user").id("10002").document(user));
            //修改doc部分属性
//            User user = new User();
//            user.setAge(101);
//            UpdateResponse<User> userUpdateResponse = client.update(
//                            x -> x.index("user").id("10002").doc(user), User.class);
            //获取doc信息
//            GetResponse<User> getResponse = client.get(x -> x.index("user").id("10002"), User.class);
            //删除doc
//            client.delete(x -> x.index("user").id("10002"));

            //批量添加doc
            /*List<User> users = new ArrayList<>();
            users.add(new User("15", "张三", 10, "女"));
            users.add(new User("16", "张四", 10, "女"));
            users.add(new User("17", "张五六", 11, "女"));
            users.add(new User("18", "张三四", 12, "女"));
            users.add(new User("19", "张三五", 13, "女"));
            users.add(new User("20", "张三六七", 14, "女"));
            users.add(new User("21", "张三1", 15, "女"));
            List<BulkOperation> bulkOperations = new ArrayList<>();
            users.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(a.getId()).document(a)))));
            client.bulk(x ->x.index("user").operations(bulkOperations));*/

            //批量删除doc
            /*List<String> strings = new ArrayList<>();
            strings.add("1");
            strings.add("2");
            strings.add("3");
            strings.add("4");
            strings.add("5");
            strings.add("6");
            strings.add("7");
            List<BulkOperation> bulkOperations = new ArrayList<>();
            strings.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.delete(c -> c.id(a)))));
            client.bulk(x ->x.index("user").operations(bulkOperations));*/

            //查询user索引所有数据
            /*SearchResponse<User> searchResponse = client.search(a -> a.index("user"), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //条件查询
            /*SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .term(c -> c
                                            .field("age")
                                            .value(d -> d
                                                    .longValue(15)
                                            )
                                    )
                            ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //分页查询 排序 过滤字段
            /*SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .from(0)
                            .size(5)
                            .sort(b -> b
                                    .field(c -> c
                                            .field("age")
                                            .order(SortOrder.Desc)
                                    )
                            )
                            .source(c -> c
                                    .filter(d -> d
                                            //不包含字段
                                            .excludes("id", "age")
                                            //包含字段
                                            .includes("name")
                                    )
                            ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //组合查询
            /*SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .bool(c -> c
                                            .mustNot(d -> d.match(e -> e.field("sex").query(f -> f.stringValue("男"))))
                                            .should(d -> d.match(e -> e.field("age").query(f -> f.longValue(10))))
                                            .should(d -> d.match(e -> e.field("age").query(f -> f.longValue(12))))
                                    )
                            ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //范围查询
            /*SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    .range(c -> c.field("age").from("10").to("12"))
                            ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/
            /*SearchResponse<User> searchResponse = client
                    .search(a -> a
                            .index("user")
                            .query(b -> b
                                    //小于等于
//                                    .range(c -> c.field("age").lte(JsonData.of("13")))
                                    //小于
//                                    .range(c -> c.field("age").lt(JsonData.of("13")))
                                    //大于等于
//                                    .range(c -> c.field("age").gte(JsonData.of("13")))
                                    //大于
//                                    .range(c -> c.field("age").gt(JsonData.of("13")))
                                    //范围
                                    .range(c -> c.field("age").from("10").to("13"))

                            )
                            .sort(b -> b.field(c -> c.field("age").order(SortOrder.Asc)))
                            .size(999999999), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //模糊查询 高亮显示
            /*SearchResponse<User> searchResponse = client.search(_0 -> _0
                    .query(_1 -> _1
                            .fuzzy(_2 -> _2
                                    .field("name")
                                    //最大偏移量
                                    .fuzziness("1")
                                    //最大查询数量
//                                    .maxExpansions(5)
                                    .value(_3 -> _3
                                            .stringValue("张四")
                                    )
                            )
                    )
                    .highlight(_4 -> _4
                            .fields("name", _5 -> _5
                                    .preTags("<font color='red'>")
                                    .postTags("</font>")
                            )
                    ), User.class);
            searchResponse.hits().hits().forEach(x -> System.out.println(x.source()));*/

            //分组操作
            /*SearchResponse<Map> search = client
                    .search(_0 -> _0
                            .aggregations("ageGroup", _1 -> _1
                                    .terms(_2 -> _2
                                            .field("age")
                                    )
                            ), Map.class);
            System.out.println(search);*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.shutdown();
                transport.close();
                restClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

制作不易,请尊重作者的劳动成果

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐