Using Predicate to search a keyset in Hazelcast
Asked Answered
R

1

1

I'm new to Hazelcast - evaluating and prototyping to see if it fits our distributed memory cache needs. One of the requirements was to be able to use wild cards to search for keys in a given map. Looking through the IMap documentation, looks like keySet(Predicate predicate) can be used. But I couldn't figure how to use the Predicate in such a way that given a wild card string, a keySet is returned containing all keys that match. An example will be helpful.

A snippet of my code. This is the client side.

IMap<String, String> mapTest1 = client.getMap("testMap");

mapTest1.put( "testKey1", "This is a Test" );
mapTest1.put( "testKey2", "This value has a long key name" );
mapTest1.put( "key3", "Another value" );
// Need a wild card search on the map, such that all keys with "%test%" will be returned.

Thanks.

Rheotropism answered 18/2, 2015 at 18:41 Comment(0)
F
2

This should do the trick if I understood your request correctly:

public class Test {

    public static void main(String[] args) {
        HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();

        IMap<String, String> map = hazelcastInstance.getMap("someMap");
        Collection<String> keys = map.keySet(
            new RegexPredicate("[a-z].*[a-z0-9]"));

        System.out.println(keys);
     }

     public static class RegexPredicate implements Predicate<String, String> {

        private String regex;
        private transient Pattern pattern;

        public RegexPredicate(String regex) {
            this.regex = regex;
        }

        @Override
        public boolean apply(Map.Entry<String, String> mapEntry) {
            if (pattern == null) {
                 pattern = Pattern.compile(regex);
            }
            Matcher matcher = pattern.matcher(mapEntry.getKey());
            return matcher.matches();
        }
    }
}
Frustration answered 18/2, 2015 at 19:5 Comment(2)
Thanks for your answer. It works perfectly when the RegexPredicate class is added to the Hazelcast cluster application and called directly from this application as shown in your example. However, when I call the map.keySet(new RegexPredicate(regexPattern) from the client, hazelcast throws a ClassNotFound exception on RegexPredicate.Rheotropism
Sure it needs to be on servers and clients. Hazelcast does not feature a distributed classloader since this would open the door to code injection into a cluster.Frustration

© 2022 - 2024 — McMap. All rights reserved.