首页 > 解决方案 > 在 Hazelcast 中查询

问题描述

如何为这个特定的数据结构查询 json 对象。

这是我的完整代码。

package com.rest.ser;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastJsonValue;
import com.hazelcast.core.IMap;
import com.hazelcast.query.SqlPredicate;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;

    
    public class User implements Serializable {

        private static final long serialVersionUID = 1L;
        private String id;
        private String name;
        private HazelcastJsonValue value;

        public User(String id, String name, HazelcastJsonValue value) {
            this.id = id;
            this.name = name;
            this.value = value;
        }
        
        private void writeObject(ObjectOutputStream out)
                throws IOException {
            out.writeObject(id);
            out.writeObject(name);
            out.writeObject(value.toString());
        }
        
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", value=" + value + "]";
        }

        private void readObject(ObjectInputStream in)
                throws IOException, ClassNotFoundException {
            id = (String) in.readObject();
            name = (String) in.readObject();
            value = new HazelcastJsonValue((String) in.readObject());
        }
    

    public static void main(String[] args)
            throws IOException, ClassNotFoundException {
        System.out.println("starts here");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(new User("1", "name", new HazelcastJsonValue("{ \"fullName\":\"John\" }\r\n" + 
                "")));
        out.flush();
        
        User user = (User) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
        HazelcastInstance instance = Hazelcast.newHazelcastInstance();

        IMap<String, User> map = instance.getMap("test_mapstore");
        map.put("1", user);
        Collection<User> output = map.values(new SqlPredicate("id='1' and name='name'"));
        System.out.println(output.toString());
        //output I'm getting [User [id=1, name=name, value={ "fullName":"John" }]]

    }
}

所以如果我想通过查询 HazelcastJsonValue 来获取 id 和 name 意味着怎么做

value.fullName='John'

value 是模型类字段名称,fullName 是 Json 对象字段...

可以这样查询吗……?

标签: javahazelcast

解决方案


你能试试这个吗?

Collection<User> users = map.values(new SqlPredicate("value.fullName", "John"));

或者

Collection<User> usersWithGradeA = map.values(Predicates.equal("value.fullName", "John"));

推荐阅读