Exforsys

Home arrow Reviews arrow Oracle Coherence

Oracle Coherence: Querying The Data Grid

Author: Packt Publishing     Published on: 24th Jun 2010

So far, you have learned how to access data in the Coherence cache using identity-based operations, such as get and put. In many cases this will be exactly what you need, but there will also be many other situations where you either won't know an object's identity or you will simply need to look up one or more objects based on attributes other than the identity.

Ads

Coherence allows you to do that by specifying a filter for set-based operations defined by the QueryMap interface, which we mentioned briefly in Chapter 3, Planning Your Caches.

Sample Code
  1.     public interface QueryMap extends Map {
  2.       Set keySet(Filter filter)
  3.       Set entrySet(Filter filter)
  4.       Set entrySet(Filter filter, Comparator comparator)
  5.       ...
  6.     }
Copyright exforsys.com


As you can see from the previous interface definition, all three methods accept a filter as the first argument, which is an instance of a class implementing a very simple com.tangosol.util.Filter interface:

Sample Code
  1.     public interface Filter {
  2.         boolean evaluate(Object o)
  3.     }
Copyright exforsys.com


Basically, the Filter interface defines a single method, evaluate, which takes an object to evaluate as an argument and returns true if the specified object satisfies the criteria defined by the filter, or false if it doesn't.

This mechanism is very flexible, as it allows you to filter your cached objects any way you want. For example, it would be quite simple to implement a filter that can be used to retrieve all the account transactions in a specific period:

Sample Code
  1.     public class TransactionFilter implements Filter {
  2.  
  3.         private Long m_accountId
  4.         private Date m_from
  5.         private Date m_to
  6.  
  7.         public TransactionFilter(Long accountId, Date from, Date to) {
  8.           m_accountId = accountId
  9.           m_from      = from
  10.           m_to        = to
  11.         }
  12.  
  13.         public boolean evaluate(Object o) {
  14.           Transaction tx = (Transaction) o
  15.           return tx.getId().getAccountId().equals(m_accountId)
  16.                  && tx.getTime().compareTo(from) >= 0
  17.                  && tx.getTime().compareTo(to) <= 0
  18.         }
  19.     }
Copyright exforsys.com


Ads

While the previous sample filter implementation is perfectly valid and will return correct results if executed against the transactions cache, it would be very cumbersome if you had to define every single query criterion in the application by implementing a custom filter class as we did previously.



 
This tutorial is part of a Oracle Coherence tutorial series. Read it from the beginning and learn yourself.

Oracle Coherence

 

Comments