简体   繁体   English

如何从 hazelcast map 中获取随机键值

[英]How get random key-value from hazelcast map

I tried to get a random element from the Map like this我试图从 Map 像这样

IMap<Integer, Integer> workWaitTasks = hazelcastInstance.getMap(WORK_WAIT_TASKS);
collectionTask = Collections.singleton(workWaitTasks.values().stream()
                .skip(workWaitTasks.isEmpty() ? 0 : new Random().nextInt(workWaitTasks.size()))
                .findFirst()
                .get());
int taskId = collectionTask.iterator().next();

but the best way I think is using predicates但我认为最好的方法是使用谓词

I read this https://docs.hazelcast.com/imdg/4.2/query/how-distributed-query-works.html#querying-with-sql-like-predicates Unfortunately this didn't help me我读了这个https://docs.hazelcast.com/imdg/4.2/query/how-distributed-query-works.html#querying-with-sql-like-predicates不幸的是这对我没有帮助

I couldn't find a way to do this我找不到办法做到这一点

in sql it is like this在 sql 中是这样的

 SELECT column FROM table
 ORDER BY RAND()
 LIMIT 1

how to make correct predicate in hazelcast?如何在榛树中做出正确的谓词?

Can you give an example please?你能举个例子吗? Help me please请帮帮我

I think there's no straightforward and effective way to do this using public API.我认为使用公共 API 没有直接有效的方法来做到这一点。 One option is using Jet:一种选择是使用 Jet:

IMap<Object, Object> sourceMap = instance.getMap("table");
IList<Object> targetList = instance.getList("result");
int samplingFactor = sourceMap.size() / 10;
Pipeline p = Pipeline.create();
p.readFrom(Sources.map(sourceMap))
        .filter(item -> item.getKey().hashCode() % samplingFactor == ThreadLocalRandom.current().nextInt(samplingFactor))
        .writeTo(Sinks.list(targetList));

instance.newJob(p).join();

The code above should add approximately 10 elements to the result list, from which it's easy to get a random entry, but it can also end up with an empty list - you can experiment with increasing the multiplier in samplingFactor to get satisfactory probability of getting some result without having to re-run the job.上面的代码应该在结果列表中添加大约 10 个元素,从中很容易获得一个随机条目,但它也可能以一个空列表结束 - 您可以尝试增加samplingFactor中的乘数以获得令人满意的获得一些元素的概率结果而不必重新运行作业。

The same might also be possible using aggregation ( IMap.aggregate ) with a custom aggregator, some colleague might provide answer:-).使用带有自定义聚合器的聚合( IMap.aggregate )也可以做到这一点,一些同事可能会提供答案:-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM