本文整理汇总了Java中org.hibernate.search.SearchFactory类的典型用法代码示例。如果您正苦于以下问题:Java SearchFactory类的具体用法?Java SearchFactory怎么用?Java SearchFactory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SearchFactory类属于org.hibernate.search包,在下文中一共展示了SearchFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: search
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* 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();
}
示例2: searchByTag
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public List<PostPO> searchByTag(Paging paigng, String tag) {
FullTextSession fullTextSession = Search.getFullTextSession(super.session());
SearchFactory sf = fullTextSession.getSearchFactory();
QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get();
org.apache.lucene.search.Query luceneQuery = qb.phrase().onField("tags").sentence(tag).createQuery();
FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery);
query.setFirstResult(paigng.getFirstResult());
query.setMaxResults(paigng.getMaxResults());
Sort sort = new Sort(new SortField("id", SortField.Type.LONG, true));
query.setSort(sort);
paigng.setTotalCount(query.getResultSize());
return query.list();
}
示例3: testProvideDispose
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* Test provide and dispose.
*/
@Test
public void testProvideDispose() {
SessionFactory sessionFactory =
locator.getService(SessionFactory.class);
Session hibernateSession = sessionFactory.openSession();
FullTextSession ftSession = Search.getFullTextSession(hibernateSession);
FulltextSearchFactoryFactory factory =
new FulltextSearchFactoryFactory(ftSession);
// Make sure that we can create a search factory.
SearchFactory searchFactory = factory.provide();
Assert.assertNotNull(searchFactory);
// Make sure we can dispose of the factory (does nothing, sadly).
factory.dispose(searchFactory);
if (hibernateSession.isOpen()) {
hibernateSession.close();
}
}
示例4: searchTest
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
@Test
public void searchTest() throws Exception {
FullTextQuery ftq = createMock(FullTextQuery.class);
FullTextSession fts = createMock(FullTextSession.class);
SearchFactory factory = createMock(SearchFactory.class);
expect(fts.getSearchFactory()).andReturn(factory);
expect(factory.getAnalyzer(Item.class)).andReturn(new StandardAnalyzer(Version.LUCENE_36));
expect(fts.createFullTextQuery(isA(Query.class), eq(Item.class))).andReturn(ftq);
expect(ftq.setProjection("title")).andReturn(ftq);
List<Object[]> results = new ArrayList<Object[]>();
results.add(new Object[] { "The Incredibles" });
expect(ftq.list()).andReturn(results);
replay(factory);
replay(ftq);
replay(fts);
}
示例5: reindexMassIndexer
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
*
* @param clazz
*/
private long reindexMassIndexer(final Class< ? > clazz)
{
final Session session = getSession();
final Criteria criteria = createCriteria(session, clazz, null, true);
final Long number = (Long) criteria.uniqueResult(); // Get number of objects to re-index (select count(*) from).
log.info("Starting (mass) re-indexing of " + number + " entries of type " + clazz.getName() + "...");
final FullTextSession fullTextSession = Search.getFullTextSession(session);
try {
fullTextSession.createIndexer(clazz)//
.batchSizeToLoadObjects(25) //
//.cacheMode(CacheMode.NORMAL) //
.threadsToLoadObjects(5) //
//.threadsForIndexWriter(1) //
.threadsForSubsequentFetching(20) //
.startAndWait();
} catch (final InterruptedException ex) {
log.error("Exception encountered while reindexing: " + ex.getMessage(), ex);
}
final SearchFactory searchFactory = fullTextSession.getSearchFactory();
searchFactory.optimize(clazz);
log.info("Re-indexing of " + number + " objects of type " + clazz.getName() + " done.");
return number;
}
示例6: search
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public List<Post> search(Paging paging, String q) throws Exception {
FullTextSession fullTextSession = Search.getFullTextSession(super.session());
SearchFactory sf = fullTextSession.getSearchFactory();
QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get();
org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("title","summary","tags").matching(q).createQuery();
FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery);
query.setFirstResult(paging.getFirstResult());
query.setMaxResults(paging.getMaxResults());
StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>");
QueryScorer queryScorer = new QueryScorer(luceneQuery);
Highlighter highlighter = new Highlighter(formatter, queryScorer);
List<PostPO> list = query.list();
List<Post> rets = new ArrayList<>(list.size());
for (PostPO po : list) {
Post m = BeanMapUtils.copy(po, 0);
// 处理高亮
String title = highlighter.getBestFragment(standardAnalyzer, "title", m.getTitle());
String summary = highlighter.getBestFragment(standardAnalyzer, "summary", m.getSummary());
if (StringUtils.isNotEmpty(title)) {
m.setTitle(title);
}
if (StringUtils.isNotEmpty(summary)) {
m.setSummary(summary);
}
rets.add(m);
}
paging.setTotalCount(query.getResultSize());
return rets;
}
示例7: optimizeIndexes
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* Do real indexes optimization.
*/
public static void optimizeIndexes() throws Exception {
FullTextSession ftSession = null;
Session session = null;
if (optimizeIndexesRunning) {
log.warn("*** Optimize indexes already running ***");
} else {
optimizeIndexesRunning = true;
log.debug("*** Begin optimize indexes ***");
try {
session = HibernateUtil.getSessionFactory().openSession();
ftSession = Search.getFullTextSession(session);
// Optimize indexes
SearchFactory searchFactory = ftSession.getSearchFactory();
searchFactory.optimize();
} catch (Exception e) {
throw e;
} finally {
optimizeIndexesRunning = false;
HibernateUtil.close(ftSession);
HibernateUtil.close(session);
}
log.debug("*** End optimize indexes ***");
}
}
示例8: checkIndexOnStartup
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
public void checkIndexOnStartup() {
//log.info("Observed event {1} from Thread {0}", Thread.currentThread().getName(), App.INIT_SUCCESS);
// See if we need to rebuild the index during startup ...
FullTextEntityManager ftEm = Search.getFullTextEntityManager(entityManager);
SearchFactory searchFactory = ftEm.getSearchFactory();
ReaderProvider readerProvider = searchFactory.getReaderProvider();
IndexReader reader = readerProvider.openReader(searchFactory.getDirectoryProviders(NodeDocumentVersion.class)[0]);
int maxDoc = 0;
try {
maxDoc = reader.maxDoc();
} finally {
readerProvider.closeReader(reader);
}
if (maxDoc == 0) {
log.warn("No objects indexed ... rebuilding Lucene search index from database ...");
long _exit = 0L;
long _entr = System.currentTimeMillis();
try {
int docs = doRebuildIndex();
_exit = System.currentTimeMillis();
log.info("Took " + (_exit - _entr)
+ " (ms) to re-build the index containing " + docs
+ " documents.");
} catch (Exception exc) {
if (exc instanceof RuntimeException) {
throw (RuntimeException) exc;
} else {
throw new RuntimeException(exc);
}
}
// build the spell checker index off of the HS index.
buildSpellCheckerIndex(searchFactory);
}
}
示例9: buildSpellCheckerIndex
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
protected void buildSpellCheckerIndex(SearchFactory searchFactory) {
IndexReader reader = null;
Directory dir = null;
long _entr = System.currentTimeMillis();
File spellCheckIndexDir = new File("lucene_index/spellcheck");
log.info("Building SpellChecker index in {0}", spellCheckIndexDir.getAbsolutePath());
ReaderProvider readerProvider = searchFactory.getReaderProvider();
try {
reader = readerProvider.openReader(searchFactory.getDirectoryProviders(NodeDocumentVersion.class)[0]);
dir = FSDirectory.open(spellCheckIndexDir);
SpellChecker spell = new SpellChecker(dir);
spell.clearIndex();
spell.indexDictionary(new LuceneDictionary(reader, NodeDocument.TEXT_FIELD));
spell.close();
dir.close();
dir = null;
long _exit = System.currentTimeMillis();
log.info("Took {1} (ms) to build SpellChecker index in {0}",
spellCheckIndexDir.getAbsolutePath(), String.valueOf((_exit - _entr)));
} catch (Exception exc) {
log.error("Failed to build spell checker index!", exc);
} finally {
if (dir != null) {
try {
dir.close();
} catch (Exception zzz) {
}
}
if (reader != null) {
readerProvider.closeReader(reader);
}
}
}
示例10: getReader
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* Get Lucene index reader.
*/
@SuppressWarnings("rawtypes")
private IndexReader getReader(FullTextSession session, Class entity) {
SearchFactory searchFactory = session.getSearchFactory();
DirectoryProvider provider = searchFactory.getDirectoryProviders(entity)[0];
ReaderProvider readerProvider = searchFactory.getReaderProvider();
return readerProvider.openReader(provider);
}
示例11: getIndexedRootEntities
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* @see MassIndexerImpl#toRootEntities
*/
protected Set<Class<?>> getIndexedRootEntities(SearchFactory searchFactory, Class<?>... selection) {
ExtendedSearchIntegrator searchIntegrator = searchFactory.unwrap(ExtendedSearchIntegrator.class);
Set<Class<?>> entities = new HashSet<Class<?>>();
// first build the "entities" set containing all indexed subtypes of "selection".
for (Class<?> entityType : selection) {
Set<Class<?>> targetedClasses = searchIntegrator.getIndexedTypesPolymorphic(new Class[] { entityType });
if (targetedClasses.isEmpty()) {
String msg = entityType.getName() + " is not an indexed entity or a subclass of an indexed entity";
throw new IllegalArgumentException(msg);
}
entities.addAll(targetedClasses);
}
Set<Class<?>> cleaned = new HashSet<Class<?>>();
Set<Class<?>> toRemove = new HashSet<Class<?>>();
//now remove all repeated types to avoid duplicate loading by polymorphic query loading
for (Class<?> type : entities) {
boolean typeIsOk = true;
for (Class<?> existing : cleaned) {
if (existing.isAssignableFrom(type)) {
typeIsOk = false;
break;
}
if (type.isAssignableFrom(existing)) {
toRemove.add(existing);
}
}
if (typeIsOk) {
cleaned.add(type);
}
}
cleaned.removeAll(toRemove);
return cleaned;
}
示例12: getReader
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
public IndexReader getReader( ) {
SearchFactory searchFactory = getFullTextSession( ).getSearchFactory( );
DirectoryProvider<?>[] providers = searchFactory
.getDirectoryProviders( entityClass );
return searchFactory.getReaderProvider( ).openReader( providers );
}
示例13: list
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* Shows the main statistics page
*/
public void list() {
IndexReader indexReader = null;
ReaderProvider readerProvider = null;
try {
SearchFactory searchFactory = Search.createFullTextSession(
this.sessionFactory.getCurrentSession()).getSearchFactory();
DirectoryProvider<?> directoryProvider = searchFactory
.getDirectoryProviders(Post.class)[0];
readerProvider = searchFactory.getReaderProvider();
indexReader = readerProvider.openReader(directoryProvider);
String indexDirectory = directoryProvider.getDirectory().toString();
indexDirectory = indexDirectory.substring(indexDirectory
.indexOf('@') + 1);
boolean indexExists = IndexReader.indexExists(indexDirectory);
this.result.include("indexExists", indexExists);
if (indexExists) {
this.result.include("numberOfDocs", indexReader.numDocs());
this.result.include("indexLocation", indexDirectory);
this.result.include("totalMessages",
this.forumRepository.getTotalMessages());
this.result.include("isLocked",
IndexReader.isLocked(indexDirectory));
this.result.include("lastModified",
new Date(IndexReader.lastModified(indexDirectory)));
}
} catch (IOException e) {
throw new ForumException(e);
} finally {
if (readerProvider != null && indexReader != null) {
readerProvider.closeReader(indexReader);
}
}
}
示例14: TestService
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
/**
* Create a new instance of our test service.
*
* @param sr ServiceRegistry
* @param f Session Factory
* @param s Hibernate Session
* @param sF Search Factory
* @param ftS Full text session
*/
@Inject
public TestService(final ServiceRegistry sr,
final SessionFactory f,
final SearchFactory sF,
final Session s,
final FullTextSession ftS) {
serviceRegistry = sr;
factory = f;
session = s;
searchFactory = sF;
ftSession = ftS;
}
示例15: getSearchFactory
import org.hibernate.search.SearchFactory; //导入依赖的package包/类
@Override
public SearchFactory getSearchFactory() {
if ( this.jpaSearchFactoryController != null ) {
return this.jpaSearchFactoryController.getSearchFactory();
}
return null;
}