Hazlecast通过查找数字来查找范围

时间:2019-12-27 04:26:59

标签: hazelcast querydsl

我是hazle-cast的新手,试图使用hazle-cast实现查找。我的情况是,我的数字范围是1-10,10-20,20-30...。如果我收到一个带有数字的请求,那么我需要返回它所属的范围,例如,如果该请求带有数字22,那么我应该返回20-30范围。 hazle-cast查询可能吗?如果您已完成类似的实现,请与您分享。

我们执行查找到的SQL查询是

select * from table where '21' between min and max

1 个答案:

答案 0 :(得分:1)

Hazelcast提供以下用于分布式查询目的的API:

  • 标准API(Hazelcast提供的编程接口,类似于Java持久性查询语言(JPQL))
  • 分布式SQL查询(com.hazelcast.query.SqlPredicate使用常规SQL where子句)

您可以在此处找到文档:https://docs.hazelcast.org/docs/latest/manual/html-single/#distributed-query

以下是SqlPredicate的示例:

public class SqlPredicateSample {

    public static class Item implements Serializable {
        String name;
        int number;

        public Item(String name, int number) {
            this.name = name;
            this.number = number;
        }

        @Override
        public String toString() {

            return "Item{"
                    + "name='" + name + '\''
                    + ", number=" + number
                    + '}';
        }
    }

    public static void main(String[] args) {
        // Start the Embedded Hazelcast Cluster Member.
        HazelcastInstance hz = Hazelcast.newHazelcastInstance();
        // Get a Distributed Map called "items"
        IMap<Integer, Item> items = hz.getMap("items");
        // Add some users to the Distributed Map
        for (int i = 0; i <= 100; i++) {
            items.put(i, new Item("name" + i , i));
        }
        Predicate sqlQuery = new SqlPredicate("name = 'name22' AND number BETWEEN 20 AND 30");
        Collection<Item> objects = items.values(sqlQuery);

        System.out.println(objects);
    }
}

作为一种变通方法,通过使用java.lang.Math.floorDiv(dividend,divisor)内置函数,您可以计算将存储在Hazelcast IMap<Integer, List>映射中的密钥以及相应的数字列表。

private void workAroundSolution() {
    HazelcastInstance client = HazelcastClient.newHazelcastClient();
    IMap<Integer, List> map = client.getMap("map");

    int sequence = 10;
    for (int i = 0; i < 5; i++) {
        int key = i + 1;
        int min = i * sequence;
        int max = key * sequence;
        List<Integer> list = IntStream.range(min, max).boxed().collect(Collectors.toList());
        map.put(i, list);
    }


    int givenValue = 22;
    int key = Math.floorDiv(givenValue, sequence);

    System.out.println("Key to look up: " + key);
    System.out.println("Range of values: " + map.get(key));
}