Esempio n. 1
0
 protected void assertIndexingKnows(BasicCache<?, ?> cache, Class<?>... types) {
   ComponentRegistry cr = ((Cache) cache).getAdvancedCache().getComponentRegistry();
   SearchIntegrator searchIntegrator = cr.getComponent(SearchIntegrator.class);
   assertNotNull(searchIntegrator);
   HashSet<Class<?>> expectedTypes = new HashSet<Class<?>>(Arrays.asList(types));
   HashSet<Class<?>> indexedTypes = new HashSet<Class<?>>(searchIntegrator.getIndexedTypes());
   assertEquals(expectedTypes, indexedTypes);
 }
 /**
  * Verifies if the indexing interceptor is aware of a specific list of types.
  *
  * @param cache the cache containing the indexes
  * @param types vararg listing the types the indexing engine should know
  */
 private void assertIndexingKnows(Cache<Object, Object> cache, Class<?>... types) {
   ComponentRegistry cr = cache.getAdvancedCache().getComponentRegistry();
   SearchIntegrator searchIntegrator = cr.getComponent(SearchIntegrator.class);
   assertNotNull(searchIntegrator);
   Map<Class<?>, EntityIndexBinding> indexBindingForEntity =
       searchIntegrator.unwrap(ExtendedSearchIntegrator.class).getIndexBindings();
   assertNotNull(indexBindingForEntity);
   Set<Class<?>> keySet = indexBindingForEntity.keySet();
   assertEquals(types.length, keySet.size());
   assertTrue(keySet.containsAll(Arrays.asList(types)));
 }
 private void assertEfficientIndexingUsed(SearchIntegrator searchIntegrator, Class<?> clazz) {
   DirectoryBasedIndexManager im =
       (DirectoryBasedIndexManager) searchIntegrator.getIndexBinding(clazz).getIndexManagers()[0];
   LuceneBackendQueueProcessor bqp = (LuceneBackendQueueProcessor) im.getBackendQueueProcessor();
   LuceneBackendResources indexResources = bqp.getIndexResources();
   IndexWorkVisitor<Void, LuceneWorkExecutor> visitor = indexResources.getWorkVisitor();
   assertTrue(
       TestingUtil.extractField(visitor, "updateDelegate") instanceof ByTermUpdateWorkExecutor);
 }
  @Test
  public void testProvidedIdMapping() throws Exception {
    FullTextSession fullTextSession = Search.getFullTextSession(openSession());
    SearchIntegrator sf = fullTextSession.getSearchFactory().unwrap(SearchIntegrator.class);

    ProvidedIdEntry person1 = new ProvidedIdEntry();
    person1.setName("Big Goat");
    person1.setBlurb("Eats grass");

    ProvidedIdEntry person2 = new ProvidedIdEntry();
    person2.setName("Mini Goat");
    person2.setBlurb("Eats cheese");

    ProvidedIdEntry person3 = new ProvidedIdEntry();
    person3.setName("Regular goat");
    person3.setBlurb("Is anorexic");

    TransactionContextForTest tc = new TransactionContextForTest();

    Work work = new Work(person1, 1, WorkType.INDEX);
    sf.getWorker().performWork(work, tc);
    work = new Work(person2, 2, WorkType.INDEX);
    sf.getWorker().performWork(work, tc);
    Work work2 = new Work(person3, 3, WorkType.INDEX);
    sf.getWorker().performWork(work2, tc);

    tc.end();

    Transaction transaction = fullTextSession.beginTransaction();

    QueryParser parser = new QueryParser("providedidentry.name", TestConstants.standardAnalyzer);
    Query luceneQuery = parser.parse("Goat");

    // we cannot use FTQuery because @ProvidedId does not provide the getter id and Hibernate
    // Hsearch Query extension
    // needs it. So we use plain HSQuery

    HSQuery query = getExtendedSearchIntegrator().createHSQuery(luceneQuery, ProvidedIdEntry.class);

    assertEquals(3, query.queryResultSize());

    transaction.commit();
    getSession().close();
  }
  private void checkIndexPresence(Cache cache) {
    SearchIntegrator searchFactory = Search.getSearchManager(cache).unwrap(SearchIntegrator.class);

    assertTrue(searchFactory.getIndexedTypes().contains(getModelFactory().getUserImplClass()));
    assertNotNull(searchFactory.getIndexManager(getModelFactory().getUserImplClass().getName()));

    assertTrue(searchFactory.getIndexedTypes().contains(getModelFactory().getAccountImplClass()));
    assertNotNull(searchFactory.getIndexManager(getModelFactory().getAccountImplClass().getName()));

    assertTrue(
        searchFactory.getIndexedTypes().contains(getModelFactory().getTransactionImplClass()));
    assertNotNull(
        searchFactory.getIndexManager(getModelFactory().getTransactionImplClass().getName()));

    assertFalse(searchFactory.getIndexedTypes().contains(getModelFactory().getAddressImplClass()));
    assertNull(searchFactory.getIndexManager(getModelFactory().getAddressImplClass().getName()));
  }
 protected MassIndexerImpl(
     SearchIntegrator searchIntegrator,
     SessionFactoryImplementor sessionFactory,
     Class<?>... entities) {
   this.extendedIntegrator = searchIntegrator.unwrap(ExtendedSearchIntegrator.class);
   this.sessionFactory = sessionFactory;
   rootEntities = toRootEntities(extendedIntegrator, entities);
   if (extendedIntegrator.isJMXEnabled()) {
     monitor = new JMXRegistrar.IndexingProgressMonitor();
   } else {
     monitor = new SimpleIndexingProgressMonitor();
   }
 }
Esempio n. 7
0
  /** Execute Lucene index query. */
  private QueryResponse executeQuery(
      AdvancedCache<byte[], byte[]> cache, SerializationContext serCtx, QueryRequest request) {
    final SearchManager searchManager = Search.getSearchManager(cache);
    final SearchIntegrator searchFactory = searchManager.getSearchFactory();
    final QueryCache queryCache = ComponentRegistryUtils.getQueryCache(cache); // optional component

    LuceneQueryParsingResult parsingResult;
    Query luceneQuery;

    if (queryCache != null) {
      KeyValuePair<String, Class> queryCacheKey =
          new KeyValuePair<String, Class>(request.getJpqlString(), LuceneQueryParsingResult.class);
      parsingResult = queryCache.get(queryCacheKey);
      if (parsingResult == null) {
        parsingResult = parseQuery(cache, serCtx, request.getJpqlString(), searchFactory);
        queryCache.put(queryCacheKey, parsingResult);
      }
    } else {
      parsingResult = parseQuery(cache, serCtx, request.getJpqlString(), searchFactory);
    }

    luceneQuery = parsingResult.getQuery();

    if (!cache.getCacheConfiguration().compatibility().enabled()) {
      // restrict on entity type
      QueryBuilder qb =
          searchFactory.buildQueryBuilder().forEntity(parsingResult.getTargetEntity()).get();
      luceneQuery =
          qb.bool()
              .must(
                  qb.keyword()
                      .onField(TYPE_FIELD_NAME)
                      .ignoreFieldBridge()
                      .ignoreAnalyzer()
                      .matching(parsingResult.getTargetEntityName())
                      .createQuery())
              .must(luceneQuery)
              .createQuery();
    }

    CacheQuery cacheQuery = searchManager.getQuery(luceneQuery, parsingResult.getTargetEntity());

    if (parsingResult.getSort() != null) {
      cacheQuery = cacheQuery.sort(parsingResult.getSort());
    }

    int projSize = 0;
    if (parsingResult.getProjections() != null && !parsingResult.getProjections().isEmpty()) {
      projSize = parsingResult.getProjections().size();
      cacheQuery =
          cacheQuery.projection(parsingResult.getProjections().toArray(new String[projSize]));
    }
    if (request.getStartOffset() > 0) {
      cacheQuery = cacheQuery.firstResult((int) request.getStartOffset());
    }
    if (request.getMaxResults() > 0) {
      cacheQuery = cacheQuery.maxResults(request.getMaxResults());
    }

    List<?> list = cacheQuery.list();
    List<WrappedMessage> results =
        new ArrayList<WrappedMessage>(projSize == 0 ? list.size() : list.size() * projSize);
    for (Object o : list) {
      if (projSize == 0) {
        results.add(new WrappedMessage(o));
      } else {
        Object[] row = (Object[]) o;
        for (int j = 0; j < projSize; j++) {
          results.add(new WrappedMessage(row[j]));
        }
      }
    }

    QueryResponse response = new QueryResponse();
    response.setTotalResults(cacheQuery.getResultSize());
    response.setNumResults(list.size());
    response.setProjectionSize(projSize);
    response.setResults(results);

    return response;
  }
Esempio n. 8
0
 private void performSearchWorks(Collection<Work> works, TransactionContext transactionContext) {
   Worker worker = searchFactory.getWorker();
   for (Work work : works) {
     worker.performWork(work, transactionContext);
   }
 }
  public void testIndexingWithWrapper() throws Exception {
    MarshallerRegistration.registerMarshallers(
        ProtobufMetadataManagerImpl.getSerializationContext(cacheManager));

    // Store some test data:
    ProtobufValueWrapper wrapper1 =
        new ProtobufValueWrapper(createMarshalledUser("Adrian", "Nistor"));
    ProtobufValueWrapper wrapper2 =
        new ProtobufValueWrapper(createMarshalledUser("John", "Batman"));

    cache.put(1, wrapper1); // todo how do we index if the key is a byte array?
    cache.put(2, wrapper2);

    SearchManager sm = Search.getSearchManager(cache);

    SearchIntegrator searchFactory = sm.unwrap(SearchIntegrator.class);
    assertNotNull(searchFactory.getIndexManager(ProtobufValueWrapper.class.getName()));

    Query luceneQuery =
        sm.buildQueryBuilderForClass(ProtobufValueWrapper.class)
            .get()
            .keyword()
            .onField("name")
            .ignoreFieldBridge()
            .ignoreAnalyzer()
            .matching("Adrian")
            .createQuery();

    List<ProtobufValueWrapper> list = sm.<ProtobufValueWrapper>getQuery(luceneQuery).list();
    assertEquals(1, list.size());
    ProtobufValueWrapper pvw = list.get(0);
    User unwrapped =
        (User)
            ProtobufUtil.fromWrappedByteArray(
                ProtobufMetadataManagerImpl.getSerializationContextInternal(cacheManager),
                pvw.getBinary());
    assertEquals("Adrian", unwrapped.getName());

    // an alternative approach ...

    Query luceneQuery2 =
        searchFactory
            .buildQueryBuilder()
            .forEntity(ProtobufValueWrapper.class)
            .get()
            .keyword()
            .onField("name")
            .ignoreFieldBridge()
            .ignoreAnalyzer()
            .matching("Adrian")
            .createQuery();

    List<EntityInfo> queryEntityInfos =
        searchFactory
            .createHSQuery(luceneQuery2, ProtobufValueWrapper.class)
            .projection("surname")
            .queryEntityInfos();

    assertEquals(1, queryEntityInfos.size());
    EntityInfo entityInfo = queryEntityInfos.get(0);
    assertEquals("Nistor", entityInfo.getProjection()[0]);
  }