第 4 章 查询嵌入式缓存
当您将 Data Grid 作为自定义应用程序的库添加时,使用嵌入式查询。
使用嵌入式查询不需要 protobuf 映射。索引和查询都在 Java 对象之上完成。
4.1. 查询嵌入式缓存 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
本节介绍如何使用名为"books"的示例缓存来查询嵌入式缓存,该缓存存储索引的 Book 实例。
在本例中,每个 Book 实例定义了索引哪些属性,并使用 Hibernate Search 注解指定一些高级索引选项,如下所示:
Book.java
package org.infinispan.sample;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.api.annotations.indexing.*;
// Annotate values with @Indexed to add them to indexes
// Annotate each field according to how you want to index it
@Indexed
public class Book {
@Keyword
String title;
@Text
String description;
@Keyword
String isbn;
@Basic
LocalDate publicationDate;
@Embedded
Set<Author> authors = new HashSet<Author>();
}
Author.java
package org.infinispan.sample;
import org.infinispan.api.annotations.indexing.Text;
public class Author {
@Text
String name;
@Text
String surname;
}
流程
配置 Data Grid 以索引"books"缓存,并将
org.infinispan.sample.Book指定为要索引的实体。<distributed-cache name="books"> <indexing path="${user.home}/index"> <indexed-entities> <indexed-entity>org.infinispan.sample.Book</indexed-entity> </indexed-entities> </indexing> </distributed-cache>获取缓存。
import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; EmbeddedCacheManager manager = new DefaultCacheManager("infinispan.xml"); Cache<String, Book> cache = manager.getCache("books");对存储在 Data Grid 缓存中的
Book实例中的字段执行查询,如下例所示:// Create an Ickle query that performs a full-text search using the ':' operator on the 'title' and 'authors.name' fields // You can perform full-text search only on indexed caches Query<Book> fullTextQuery = cache.query("FROM org.infinispan.sample.Book b WHERE b.title:'infinispan' AND b.authors.name:'sanne'"); // Use the '=' operator to query fields in caches that are indexed or not // Non full-text operators apply only to fields that are not analyzed Query<Book> exactMatchQuery= cache.query("FROM org.infinispan.sample.Book b WHERE b.isbn = '12345678' AND b.authors.name : 'sanne'"); // You can use full-text and non-full text operators in the same query Query<Book> query= cache.query("FROM org.infinispan.sample.Book b where b.authors.name : 'Stephen' and b.description : (+'dark' -'tower')"); // Get the results List<Book> found=query.execute().list();