@Override public FullTextQuery getFTSQuery(String filterText, final Class<?> entityType, Integer maxResults, String... fields) { // entityManager para busquedas de tipo FTS final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager); // se crea el query usando Hibernate Search query DSL final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(entityType).get(); // se crea el query sobre los campos indicados final Query query = queryBuilder.keyword().onFields(fields).matching(filterText.trim()).createQuery(); // se enmascara el query de Lucene en uno de Hibernate final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, entityType); // se define la cantidad maxima de resultados si es mayor a cero if (maxResults > 0) { jpaQuery.setMaxResults(maxResults); } // se retorna el query listo para ejecución o para inyeccion de criterias return jpaQuery; }
@Transactional @Override public Page<Book> search(String query, Pageable page) { FullTextEntityManager manager = this.getFullTextEntityManager(); QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get(); Query luceneQuery = builder.keyword().fuzzy() .onFields("author", "title", "lang", "description", "isbn", "genre", "location").matching(query) .createQuery(); FullTextQuery q = manager.createFullTextQuery(luceneQuery, Book.class); q.setProjection(FullTextQuery.THIS, FullTextQuery.SCORE); long total = q.getResultSize(); q.setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()); @SuppressWarnings("unchecked") List<Object[]> result = q.getResultList(); List<Book> fine = new LinkedList<>(); for (Object[] i : result) { fine.add((Book) i[0]); } return new PageImpl<>(fine, page, total); }
@Test public void searchSubscriptions() throws Exception { DataServiceBean bean = spy(new DataServiceBean()); SubscriptionSearchServiceBean ssb = spy( new SubscriptionSearchServiceBean()); doReturn(bean).when(ssb).getDm(); FullTextEntityManager ftem = mock(FullTextEntityManager.class, Mockito.RETURNS_DEEP_STUBS); doReturn(ftem).when(ssb).getFtem(); Subscription sub = new Subscription(); sub.setKey(1L); FullTextQuery fullTextQuery = mock(FullTextQuery.class); when(ftem.createFullTextQuery(any(BooleanQuery.class), any(Class.class))).thenReturn(fullTextQuery); doReturn(Arrays.asList(sub)).when(fullTextQuery).getResultList(); Collection<Long> result = ssb.searchSubscriptions("searchphrase"); assertTrue(result.contains(new Long(1L))); }
/** * Searches the lucene store for a specific query * * @param <T> What type of information are we searching * @param clazz The class of the information we are searching * @param queryText The query text * @return list of entities * @throws ParseException the parse exception */ public final <T extends BaseEntity> List<Object[]> search(final Class<T> clazz, final String queryText) throws ParseException { final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); final SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); final QueryParser parser = new MultiFieldQueryParser(getClassLuceneFields(clazz), searchFactory.getAnalyzer(clazz)); final List<Query> parsedQueries = Arrays.stream(queryText.split("AND")) .map(e -> parseQuery(e, parser)) .filter(Objects::nonNull) .collect(Collectors.toList()); final BooleanQuery.Builder bq = new BooleanQuery.Builder(); parsedQueries.forEach(e -> bq.add(e, BooleanClause.Occur.MUST)); final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(bq.build(), clazz); jpaQuery.setProjection(ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION, ProjectionConstants.THIS); return (List<Object[]>) jpaQuery.getResultList(); }
@Override public FullTextQuery getFTSWildcardQuery(String filterText, final Class<?> entityType, Integer maxResults, String field) { // entityManager para busquedas de tipo FTS final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager); // se crea el query usando Hibernate Search query DSL final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(entityType).get(); // se crea el query sobre los campos indicados final Query query = queryBuilder.phrase().onField(field).sentence(filterText.trim()).createQuery(); // se enmascara el query de Lucene en uno de Hibernate final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, entityType); // se define la cantidad maxima de resultados si es mayor a cero if (maxResults > 0) { jpaQuery.setMaxResults(maxResults); } // se retorna el query listo para ejecución o para inyeccion de criterias return jpaQuery; }
public void index(Class<?> type) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); if (type == Article.class) { for (int i = 0; i < articleDao.count(); i += 20) { List<Article> articles = articleDao.findList(i, 20, null, null); for (Article article : articles) { fullTextEntityManager.index(article); } fullTextEntityManager.flushToIndexes(); fullTextEntityManager.clear(); articleDao.clear(); } } else if (type == Product.class) { for (int i = 0; i < productDao.count(); i += 20) { List<Product> products = productDao.findList(i, 20, null, null); for (Product product : products) { fullTextEntityManager.index(product); } fullTextEntityManager.flushToIndexes(); fullTextEntityManager.clear(); productDao.clear(); } } }
/** * Call at the startup of the server. * * - Enables Hibernate's FullTextEntityManager for Full-text searching. * - Initializes roles in database */ public void initialize() { logger.info("Linking entityManager."); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); logger.info(String.format("entityManager: %s linked.", entityManager)); try { logger.info("Beginning to index data."); fullTextEntityManager.createIndexer().startAndWait(); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("Index complete."); // Initialize user roles in database Role publicRole = createRole(1, "ROLE_PUBLIC"); roleRepository.save(publicRole); Role adminRole = createRole(2, "ROLE_ADMIN"); roleRepository.save(adminRole); }
@Transactional @Override public Collection<User> search(String query) { FullTextEntityManager manager = this.getFullTextEntityManager(); QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder().forEntity(User.class).get(); Query luceneQuery = builder.keyword().fuzzy() .onFields("username").matching(query) .createQuery(); FullTextQuery q = manager.createFullTextQuery(luceneQuery, User.class); q.setProjection(FullTextQuery.THIS, FullTextQuery.SCORE); @SuppressWarnings("unchecked") List<Object[]> result = q.getResultList(); List<User> fine = new LinkedList<>(); result.stream().forEach((i) -> { fine.add((User) i[0]); }); return fine; }
@Override public List<Product> searchByText(String text) { Product productEntity = newInstance(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder() .forEntity(productEntity.getClass()).get(); if (!Strings.isNullOrEmpty(text)) { Query query = qb.keyword().onField("name").andField("details").andField("technicalDetails").matching(text) .createQuery(); javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query, productEntity.getClass()); List<Product> result = persistenceQuery.getResultList(); if (CollectionUtils.isNotEmpty(result)) { for (Product product : result) { loadImagesFromQuantities(product.getQuantities()); } } return result; } return Collections.emptyList(); }
protected void reindexClasses(FullTextEntityManager fullTextEntityManager, Set<Class<?>> entityClasses) throws InterruptedException { int batchSize = propertyService.get(HIBERNATE_SEARCH_REINDEX_BATCH_SIZE); int loadThreads = propertyService.get(HIBERNATE_SEARCH_REINDEX_LOAD_THREADS); if (LOGGER.isInfoEnabled()) { LOGGER.info("Targets for indexing job: {}", entityClasses); } for (Class<?> clazz : entityClasses) { ProgressMonitor progressMonitor = new ProgressMonitor(); Thread t = new Thread(progressMonitor); LOGGER.info(String.format("Reindexing %1$s.", clazz)); t.start(); MassIndexer indexer = fullTextEntityManager.createIndexer(clazz); indexer.batchSizeToLoadObjects(batchSize) .threadsToLoadObjects(loadThreads) .cacheMode(CacheMode.NORMAL) .progressMonitor(progressMonitor) .startAndWait(); progressMonitor.stop(); t.interrupt(); LOGGER.info(String.format("Reindexing %1$s done.", clazz)); } }
@Nullable @SuppressWarnings({ CompilerWarnings.UNCHECKED }) private Long[] processKeywords(EntityManager entityManager, @Nullable Integer maxResults) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(this.entityImplClass).get(); BooleanJunction<?> conjunction = queryBuilder.bool(); PropertyMetadata keywordPropMetadata; for (String keywordPropName : this.keywords.keySet()) { conjunction = conjunction.must(queryBuilder.keyword() .onFields((keywordPropMetadata = this.entityPropMetadatas.get(keywordPropName)).getLowercaseFieldName(), keywordPropMetadata.getEdgeNgramFieldName(), keywordPropMetadata.getNgramFieldName(), keywordPropMetadata.getPhoneticFieldName()) .matching(StringUtils.join(this.keywords.get(keywordPropName), StringUtils.SPACE)).createQuery()); } FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(new InterceptingQuery(conjunction.createQuery()), this.entityImplClass); fullTextQuery.setProjection(ProjectionConstants.ID); if (maxResults != null) { fullTextQuery.setMaxResults(maxResults); } return ((List<Object[]>) fullTextQuery.getResultList()).stream().map(fullTextResult -> ((Long) fullTextResult[0])).toArray(Long[]::new); }
@SuppressWarnings("unchecked") public <T> List<T> executeSearchQuery( RestSearchKey key, Class<T> typeClass, FullTextEntityManager fullTextEntityManager, QueryBuilder queryBuilder, Map<String, Query> crtsMap ) { FullTextQuery fullTextQuery = createFullTextQuery(typeClass, fullTextEntityManager, queryBuilder, crtsMap); if(key.hasOrders()){ hibernateSearchBuilder.defineOrder(key, fullTextQuery); } hibernateSearchBuilder.definePaging(key, fullTextQuery); return fullTextQuery.getResultList(); }
private <T> FullTextQuery createFullTextQuery(Class<T> typeClass, FullTextEntityManager fullTextEntityManager, QueryBuilder queryBuilder, Map<String, Query> crtsMap) { BooleanJunction<?> booleanJunction = hibernateSearchBuilder.createFinalBooleanJunction( queryBuilder, crtsMap); FullTextQuery fullTextQuery = null; if(booleanJunction == null){ fullTextQuery = fullTextEntityManager.createFullTextQuery( queryBuilder.all().createQuery(), typeClass); } else { fullTextQuery = fullTextEntityManager.createFullTextQuery( booleanJunction.createQuery(), typeClass); } return fullTextQuery; }
@SuppressWarnings("unchecked") public <T> List<T> find(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) { // log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties}); FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager); Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties); if (query == null) { return null; } FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( // query, clazz); if (sp.getMaxResults() > 0) { ftq.setMaxResults(sp.getMaxResults()); } return ftq.getResultList(); }
@SuppressWarnings("unchecked") public <T> List<Serializable> findId(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) { //log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties}); FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager); Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties); if (query == null) { return null; } FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( // query, clazz); ftq.setProjection("id"); if (sp.getMaxResults() > 0) { ftq.setMaxResults(sp.getMaxResults()); } List<Serializable> ids = newArrayList(); List<Object[]> resultList = ftq.getResultList(); for (Object[] result : resultList) { ids.add((Serializable) result[0]); } return ids; }
@Override public Query build(FullTextEntityManager fullTextEntityManager, SearchParameters searchParameters, List<SingularAttribute<?, ?>> availableProperties) { List<String> clauses = getAllClauses(searchParameters, searchParameters.getTerms(), availableProperties); StringBuilder query = new StringBuilder(); query.append("+("); for (String clause : clauses) { if (query.length() > 2) { query.append(" AND "); } query.append(clause); } query.append(")"); if (query.length() == 3) { return null; } //log.debug("Lucene query: {}", query); try { return new QueryParser(availableProperties.get(0).getName(), fullTextEntityManager.getSearchFactory().getAnalyzer("custom")) .parse(query.toString()); } catch (Exception e) { throw propagate(e); } }
@Test @Transactional public void searchAdherentSortOnName() throws Exception { // Given adherent.setNom("FERRÉ"); adherentRepository.saveAndFlush(adherent); final Adherent secondAdherent = new Adherent(); secondAdherent.setPrenom(DEFAULT_PRENOM); secondAdherent.setNom("BERRUBÉ"); adherentRepository.saveAndFlush(secondAdherent); final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.flushToIndexes(); // When restAdherentMockMvc.perform(get("/api/adherents/search?criteria=eRR&sort=nom").accept(TestUtil.APPLICATION_JSON_UTF8)).andExpect(status().isOk()) .andExpect(jsonPath("$.[*].nom").value(contains("BERRUBÉ", "FERRÉ"))); }
public List<AuditFlow> searchAuditFlowPhrase(String textSearch, int fromRownum, int maxRownums) { FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(em); QueryBuilder qb = fullTextEntityManager.getSearchFactory() .buildQueryBuilder() .forEntity(AuditFlow.class) .get(); Query luceneQuery = qb.phrase() .onField("error") .sentence(textSearch) .createQuery(); return fullTextEntityManager.createFullTextQuery(luceneQuery, AuditFlow.class) .setFirstResult(fromRownum) .setMaxResults(maxRownums) .getResultList(); }
public List<String> extractCategories() { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity( Categories.class ).get(); org.apache.lucene.search.Query query = queryBuilder.all().createQuery(); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Categories.class ); fullTextQuery.setProjection( FullTextQuery.ID , "category" ); Sort sort = new Sort( new SortField( "category" , SortField.STRING ) ); fullTextQuery.setSort( sort ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); List<String> results = fullTextQuery.getResultList(); return results; }
public Map<Integer , List<Products>> extractProducts( String id , int page ) { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity( Products.class ).get(); org.apache.lucene.search.Query query = queryBuilder.keyword().onField( "category.id" ).matching( id ).createQuery(); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Products.class ); Sort sort = new Sort( new SortField( "price" , SortField.DOUBLE ) ); fullTextQuery.setSort( sort ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); fullTextQuery.setFirstResult( page * 3 ); fullTextQuery.setMaxResults( 3 ); List<Products> results = fullTextQuery.getResultList(); Map<Integer , List<Products>> results_and_total = new HashMap<Integer , List<Products>>(); results_and_total.put( fullTextQuery.getResultSize() , results ); return results_and_total; }
public List<Products> searchProducts( String search ) { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity( Products.class ).get(); org.apache.lucene.search.Query query = queryBuilder.keyword().onField( "product" ).matching( search ).createQuery(); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Products.class ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); fullTextQuery.setMaxResults( 3 ); List results = fullTextQuery.getResultList(); return results; }
public List<Products> extractPromotionalProducts() { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); org.apache.lucene.search.Query query = NumericRangeQuery.newDoubleRange( "old_price" , 0.0d , 1000d , false , true ); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Products.class ); Sort sort = new Sort( new SortField( "price" , SortField.DOUBLE ) ); fullTextQuery.setSort( sort ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); List results = fullTextQuery.getResultList(); return results; }
public Customers extractCustomer( String email , String password ) { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager( em ); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity( Customers.class ).get(); org.apache.lucene.search.Query query = queryBuilder.bool().must( queryBuilder.keyword() .onField( "email" ).matching( email ).createQuery() ).must( queryBuilder.keyword() .onField( "password" ).matching( password ).createQuery() ).createQuery(); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( query , Customers.class ); //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); List results = fullTextQuery.getResultList(); if ( results.isEmpty() ) { return null; } return ( Customers ) results.get( 0 ); }
@SuppressWarnings("unchecked") private <T> FullTextQuery getQuery(Class<? extends T> type, TermSelector<T, ?> termSelector) { FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager); Query query; if (termSelector instanceof StringTermSelector) { query = luceneQueryBuilder.build(fullTextEntityManager, (StringTermSelector<T>) termSelector, type); } else if (termSelector instanceof ObjectTermSelector) { query = luceneQueryBuilder.build(fullTextEntityManager, (ObjectTermSelector<T>) termSelector, type); } else { throw new RuntimeException("Unknown TermSelector: " + termSelector.getClass().getName()); } if (query == null) { return null; } logger.debug("Query: {}.", query.toString()); FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( // query, type); return ftq; }
@Test public void test() { final String testValue = "test"; assertThat(entityWithFullTextRepository.findCount(findByValue(testValue))).isEqualTo(0); EntityWithFullText entityWithFullText = new EntityWithFullText(); entityWithFullText.setValue(testValue); entityWithFullText = entityWithFullTextRepository.save(entityWithFullText); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.index(entityWithFullText); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.flush(); assertThat(entityWithFullTextRepository.find(findByValue(testValue))).containsExactly(entityWithFullText); }
@Test public void test() { final String testValue = "test"; assertThat(entityWithMultipleFullTextRepository.findCount(findByValue(testValue))).isEqualTo(0); EntityWithMultipleFullText entityWithMultipleFullText = new EntityWithMultipleFullText(); entityWithMultipleFullText.setValue1(testValue); entityWithMultipleFullText.setValue2("abcdef"); entityWithMultipleFullText = entityWithMultipleFullTextRepository.save(entityWithMultipleFullText); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.index(entityWithMultipleFullText); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.flush(); assertThat(entityWithMultipleFullTextRepository.find(findByValue(testValue))).containsExactly(entityWithMultipleFullText); }
@Test public void deep_test() { final String testValue = "test"; assertThat(entityWithMultipleFullTextRepository.findCount(findByDeepValue(testValue))).isEqualTo(0); EntityWithMultipleFullText entityWithMultipleFullText = new EntityWithMultipleFullText(); entityWithMultipleFullText.setValue1("abcdef"); EntityWithFullText entityWithFullText = new EntityWithFullText(); entityWithFullText.setValue(testValue); entityWithMultipleFullText.setEntityWithFullText(entityWithFullText); entityWithMultipleFullText = entityWithMultipleFullTextRepository.save(entityWithMultipleFullText); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.index(entityWithMultipleFullText); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.flush(); assertThat(entityWithMultipleFullTextRepository.find(findByDeepValue(testValue))).containsExactly(entityWithMultipleFullText); }
@Test public void test() { final Integer testValue = 1995; assertThat(entityWithFullTextIntegerRepository.findCount(findByValue(testValue))).isEqualTo(0); EntityWithFullTextInteger entityWithFullTextInteger = new EntityWithFullTextInteger(); entityWithFullTextInteger.setValue(testValue); entityWithFullTextInteger = entityWithFullTextIntegerRepository.save(entityWithFullTextInteger); EntityWithFullTextInteger another = new EntityWithFullTextInteger(); another.setValue(1994); entityWithFullTextIntegerRepository.save(another); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.index(entityWithFullTextInteger); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.flush(); assertThat(entityWithFullTextIntegerRepository.find(findByValue(testValue))).containsExactly(entityWithFullTextInteger); }
@PostConstruct public void recreateIndex() throws Exception { log.debug("SearchConfiguration - creating full-text index"); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); Future<?> indexResult = fullTextEntityManager.createIndexer().start(); Futures.addCallback(JdkFutureAdapters.listenInPoolThread(indexResult), new FutureCallback<Object>() { @Override public void onSuccess(Object result) { log.debug("SearchConfiguration - finished creating full-text index"); } @Override public void onFailure(Throwable t) { log.error("SearchConfiguration - Failed creating full-text index", t); } }); }
@Override public List<Owner> search(String searchterm) { FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager); QueryBuilder qb = fullTextEntityManager.getSearchFactory() .buildQueryBuilder().forEntity( Owner.class ).get(); org.apache.lucene.search.Query query = qb .keyword() .onFields("firstName", "lastName", "city", "pets.name") .matching(searchterm) .createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Owner.class); // execute search @SuppressWarnings("unchecked") List<Owner> result = persistenceQuery.getResultList(); return result; }
@Override public List<Vet> search(String searchterm){ FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager); QueryBuilder qb = fullTextEntityManager.getSearchFactory() .buildQueryBuilder().forEntity( Vet.class ).get(); org.apache.lucene.search.Query query = qb .keyword() .onFields("firstName", "lastName") .matching(searchterm) .createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Vet.class); // execute search @SuppressWarnings("unchecked") List<Vet> result = persistenceQuery.getResultList(); return result; }
public void addRESTServiceLinks() { FullTextEntityManager oFullTextEntityManager = PersistenceUtil.getFullTextEntityManager(); PersistenceUtil.beginEntityManagerTransaction(); QueryBuilder oQueryBuilder = oFullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(RESTServiceModel.class).get(); org.apache.lucene.search.Query oLuceneQuery = oQueryBuilder.keyword().onFields("wsProvider", "wsName", "wsDescription", "wsKeywords").matching(searchKeyword).createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query oJpaQuery = oFullTextEntityManager.createFullTextQuery(oLuceneQuery, RESTServiceModel.class); // execute search List<RESTServiceModel> RESTServiceList =(List<RESTServiceModel>) oJpaQuery.getResultList(); Iterator<RESTServiceModel> iteratorOfRESTServiceList = RESTServiceList.iterator(); while(iteratorOfRESTServiceList.hasNext()) { RESTServiceModel oRESTService = iteratorOfRESTServiceList.next(); oSearch.getLinkList().add(new Link(String.format("%saccount/%d/RESTService/%d",oApplicationUri.getBaseUri(),oRESTService.getAccount().getAccountId() ,oRESTService.getRESTServiceId()),oRESTService.getBaseUri(),"GET","RESTService")); } PersistenceUtil.endEntityManagerTransaction(); }
public void addResourceLinks() { FullTextEntityManager oFullTextEntityManager = PersistenceUtil.getFullTextEntityManager(); PersistenceUtil.beginEntityManagerTransaction(); QueryBuilder oQueryBuilder = oFullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(ResourceModel.class).get(); org.apache.lucene.search.Query oLuceneQuery = oQueryBuilder.keyword().onFields("resourceName", "resourceDescription","resourceKeywords").matching(searchKeyword).createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query oJpaQuery = oFullTextEntityManager.createFullTextQuery(oLuceneQuery, ResourceModel.class); // execute search List<ResourceModel> resourceList =(List<ResourceModel>) oJpaQuery.getResultList(); Iterator<ResourceModel> iteratorOfResourceList = resourceList.iterator(); while(iteratorOfResourceList.hasNext()) { ResourceModel oResource = iteratorOfResourceList.next(); oSearch.getLinkList().add(new Link(String.format("%saccount/%d/RESTService/%d/resource/%d",oApplicationUri.getBaseUri(),oResource.getRESTService().getAccount().getAccountId(),oResource.getRESTService().getRESTServiceId(),oResource.getResourceId()),oResource.getRelativeUri(),"GET","resource")); } PersistenceUtil.endEntityManagerTransaction(); }
public void addRESTMethodLinks() { FullTextEntityManager oFullTextEntityManager = PersistenceUtil.getFullTextEntityManager(); PersistenceUtil.beginEntityManagerTransaction(); QueryBuilder oQueryBuilder = oFullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(RESTMethodModel.class).get(); org.apache.lucene.search.Query oLuceneQuery = oQueryBuilder.keyword().onFields("methodDescription", "methodIdentifier","methodKeywords").matching(searchKeyword).createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query oJpaQuery = oFullTextEntityManager.createFullTextQuery(oLuceneQuery, RESTMethodModel.class); // execute search List<RESTMethodModel> RESTMethodList =(List<RESTMethodModel>) oJpaQuery.getResultList(); Iterator<RESTMethodModel> iteratorOfRESTMethodList = RESTMethodList.iterator(); while(iteratorOfRESTMethodList.hasNext()) { RESTMethodModel oRESTMethod = iteratorOfRESTMethodList.next(); oSearch.getLinkList().add(new Link(String.format("%saccount/%d/RESTService/%d/resource/%d/RESTMethod/%d",oApplicationUri.getBaseUri(),oRESTMethod.getResource().getRESTService().getAccount().getAccountId(),oRESTMethod.getResource().getRESTService().getRESTServiceId(),oRESTMethod.getResource().getResourceId(),oRESTMethod.getRESTMethodId()),oRESTMethod.getMethodIdentifier(),"GET","RESTMethod")); } PersistenceUtil.endEntityManagerTransaction(); }