List of usage examples for com.liferay.portal.kernel.search SearchContext getQueryConfig
public QueryConfig getQueryConfig()
From source file:com.library.slayer.service.impl.LMSBookLocalServiceImpl.java
License:Open Source License
public List<LMSBook> advanceSearchAll(long companyId, long groupId, String title, String author, String desc, String type) {//from w w w .j a v a2 s . c om SearchContext searchContext = new SearchContext(); searchContext.setCompanyId(companyId); searchContext.setEntryClassNames(CLASS_NAMES); BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext); contextQuery.addRequiredTerm(Field.COMPANY_ID, companyId); contextQuery.addRequiredTerm(Field.PORTLET_ID, Long.toString(ClassNameLocalServiceUtil.getClassNameId(LMSBook.class))); BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext); fullQuery.setQueryConfig(searchContext.getQueryConfig()); try { fullQuery.add(contextQuery, BooleanClauseOccur.MUST); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext); Hits hits = null; if (Validator.isNotNull(title)) { Sort sort = new Sort(Field.TITLE, true); searchContext.setSorts(new Sort[] { sort }); fullQuery = createQuery(Field.TITLE, title, searchContext, fullQuery); } if (Validator.isNotNull(author)) { fullQuery = createQuery(Field.NAME, author, searchContext, fullQuery); } if (Validator.isNotNull(desc)) { fullQuery = createQuery(Field.DESCRIPTION, desc, searchContext, fullQuery); } if (searchQuery.clauses().size() > 0) { try { fullQuery.add(searchQuery, BooleanClauseOccur.MUST); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { hits = SearchEngineUtil.search(searchContext, fullQuery); } catch (SearchException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<LMSBook> books = new ArrayList<LMSBook>(); if (hits != null && hits.getLength() > 0) { for (Document document : hits.getDocs()) { long bookId = Long.parseLong(document.get(Field.ENTRY_CLASS_PK)); try { LMSBook book = LMSBookLocalServiceUtil.getLMSBook(bookId); books.add(book); } catch (PortalException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return books; }
From source file:com.liferay.asset.internal.util.AssetHelperImpl.java
License:Open Source License
private AssetSearcher _getAssetSearcher(SearchContext searchContext, AssetEntryQuery assetEntryQuery, int start, int end) throws Exception { Indexer<?> searcher = AssetSearcher.getInstance(); AssetSearcher assetSearcher = (AssetSearcher) searcher; assetSearcher.setAssetEntryQuery(assetEntryQuery); Layout layout = assetEntryQuery.getLayout(); if (layout != null) { searchContext.setAttribute(Field.LAYOUT_UUID, layout.getUuid()); }/*from w w w . j a v a 2 s . c om*/ String ddmStructureFieldName = (String) assetEntryQuery.getAttribute("ddmStructureFieldName"); Serializable ddmStructureFieldValue = assetEntryQuery.getAttribute("ddmStructureFieldValue"); if (Validator.isNotNull(ddmStructureFieldName) && Validator.isNotNull(ddmStructureFieldValue)) { searchContext.setAttribute("ddmStructureFieldName", ddmStructureFieldName); searchContext.setAttribute("ddmStructureFieldValue", ddmStructureFieldValue); } String paginationType = GetterUtil.getString(assetEntryQuery.getPaginationType(), "more"); if (!paginationType.equals("none") && !paginationType.equals("simple")) { searchContext.setAttribute("paginationType", paginationType); } searchContext.setClassTypeIds(assetEntryQuery.getClassTypeIds()); searchContext.setEnd(end); searchContext.setGroupIds(assetEntryQuery.getGroupIds()); if (Validator.isNull(assetEntryQuery.getKeywords())) { QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.setScoreEnabled(false); } else { searchContext.setLike(true); } searchContext.setSorts(_getSorts(assetEntryQuery, searchContext.getLocale())); searchContext.setStart(start); return assetSearcher; }
From source file:com.liferay.asset.search.test.AssetSearcherStagingTest.java
License:Open Source License
@Test public void testSiteRolePermissions() throws Exception { Role role = addRole(RoleConstants.TYPE_SITE); String className = "com.liferay.journal.model.JournalArticle"; RoleTestUtil.addResourcePermission(role, className, ResourceConstants.SCOPE_GROUP_TEMPLATE, "0", ActionKeys.VIEW);/* ww w .j ava 2 s . co m*/ User user = addUser(); ServiceTestUtil.setUser(user); addUserGroupRole(user, role); addJournalArticle(); GroupTestUtil.enableLocalStaging(_group); SearchContext searchContext = getSearchContext(); Group stagingGroup = _group.getStagingGroup(); searchContext.setGroupIds(new long[] { stagingGroup.getGroupId() }); searchContext.setUserId(user.getUserId()); QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.addSelectedFieldNames(Field.GROUP_ID, Field.STAGING_GROUP); AssetEntryQuery assetEntryQuery = getAssetEntryQuery(className); Hits hits = search(assetEntryQuery, searchContext); Document[] documents = hits.getDocs(); DocumentsAssert.assertCount(hits.toString(), documents, Field.COMPANY_ID, 1); Document document = documents[0]; assertField(document, Field.GROUP_ID, String.valueOf(stagingGroup.getGroupId())); assertField(document, Field.STAGING_GROUP, StringPool.TRUE); }
From source file:com.liferay.asset.search.test.AssetUtilSearchSortTest.java
License:Open Source License
@Test public void testPriority() throws Exception { double[] priorities = { 10, 1, 40, 5.3 }; for (double priority : priorities) { addJournalArticle(serviceContext -> serviceContext.setAssetPriority(priority)); }/* w w w .j ava 2s. co m*/ SearchContext searchContext = createSearchContext(); QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.addSelectedFieldNames(Field.PRIORITY); AssetEntryQuery assetEntryQuery = createAssetEntryQueryOrderBy(Field.PRIORITY); Hits hits = _assetHelper.search(searchContext, assetEntryQuery, QueryUtil.ALL_POS, QueryUtil.ALL_POS); DocumentsAssert.assertValues((String) searchContext.getAttribute("queryString"), hits.getDocs(), Field.PRIORITY, Arrays.asList("1.0", "5.3", "10.0", "40.0")); }
From source file:com.liferay.bookmarks.service.impl.BookmarksEntryLocalServiceImpl.java
License:Open Source License
@Override public Hits search(long groupId, long userId, long creatorUserId, int status, int start, int end) throws PortalException { Indexer<BookmarksEntry> indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class.getName()); SearchContext searchContext = new SearchContext(); searchContext.setAttribute(Field.STATUS, status); if (creatorUserId > 0) { searchContext.setAttribute(Field.USER_ID, String.valueOf(creatorUserId)); }/*from w w w . java 2s.c o m*/ searchContext.setAttribute("paginationType", "none"); Group group = groupLocalService.getGroup(groupId); searchContext.setCompanyId(group.getCompanyId()); searchContext.setEnd(end); searchContext.setGroupIds(new long[] { groupId }); searchContext.setSorts(new Sort(Field.MODIFIED_DATE, true)); searchContext.setStart(start); searchContext.setUserId(userId); QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.setHighlightEnabled(false); queryConfig.setScoreEnabled(false); return indexer.search(searchContext); }
From source file:com.liferay.calendar.search.test.CalendarSearchFixture.java
License:Open Source License
public SearchContext getSearchContext(String keywords, Locale locale) { SearchContext searchContext = new SearchContext(); try {/*from w w w . j a va2s. c om*/ searchContext.setCompanyId(TestPropsValues.getCompanyId()); searchContext.setUserId(getUserId()); } catch (PortalException pe) { throw new RuntimeException(pe); } searchContext.setGroupIds(new long[] { _group.getGroupId() }); searchContext.setKeywords(keywords); searchContext.setLocale(Objects.requireNonNull(locale)); QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.setSelectedFieldNames(StringPool.STAR); return searchContext; }
From source file:com.liferay.configuration.admin.web.internal.portlet.action.SearchMVCRenderCommand.java
License:Open Source License
@Override public String render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException { Indexer indexer = _indexerRegistry.nullSafeGetIndexer(ConfigurationModel.class); SearchContext searchContext = new SearchContext(); searchContext.setAndSearch(false);/*from w ww.j a va 2s.c om*/ searchContext.setCompanyId(CompanyConstants.SYSTEM); searchContext.setLocale(renderRequest.getLocale()); String keywords = renderRequest.getParameter("keywords"); if (Validator.isNotNull(keywords)) { searchContext.setKeywords(keywords); } QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.setHighlightEnabled(true); queryConfig.setLocale(renderRequest.getLocale()); queryConfig.setScoreEnabled(true); try { Hits hits = indexer.search(searchContext); Document[] documents = hits.getDocs(); Map<String, ConfigurationModel> configurationModels = _configurationModelRetriever .getConfigurationModels(); List<ConfigurationModel> searchResults = new ArrayList<>(documents.length); for (Document document : documents) { String configurationModelId = document.get(FieldNames.CONFIGURATION_MODEL_ID); ConfigurationModel configurationModel = configurationModels.get(configurationModelId); if (configurationModel == null) { String configurationModelFactoryId = document.get(FieldNames.CONFIGURATION_MODEL_FACTORY_PID); configurationModel = configurationModels.get(configurationModelFactoryId); } if (configurationModel != null) { searchResults.add(configurationModel); } } ConfigurationModelIterator configurationModelIterator = new ConfigurationModelIterator(searchResults); renderRequest.setAttribute(ConfigurationAdminWebKeys.CONFIGURATION_MODEL_ITERATOR, configurationModelIterator); renderRequest.setAttribute(ConfigurationAdminWebKeys.RESOURCE_BUNDLE_LOADER_PROVIDER, _resourceBundleLoaderProvider); } catch (Exception e) { throw new PortletException(e); } return "/view.jsp"; }
From source file:com.liferay.configuration.admin.web.internal.search.ConfigurationModelIndexer.java
License:Open Source License
@Override public BooleanQuery getFullQuery(SearchContext searchContext) throws SearchException { try {/*from w ww . j a v a 2s.c om*/ BooleanFilter fullQueryBooleanFilter = new BooleanFilter(); fullQueryBooleanFilter.addRequiredTerm(Field.ENTRY_CLASS_NAME, getClassName()); BooleanQuery fullQuery = createFullQuery(fullQueryBooleanFilter, searchContext); fullQuery.setQueryConfig(searchContext.getQueryConfig()); return fullQuery; } catch (SearchException se) { throw se; } catch (Exception e) { throw new SearchException(e); } }
From source file:com.liferay.document.library.repository.cmis.internal.CMISRepository.java
License:Open Source License
@Override public Hits search(SearchContext searchContext, Query query) throws SearchException { try {//www .j ava 2 s. c o m QueryConfig queryConfig = searchContext.getQueryConfig(); queryConfig.setScoreEnabled(false); return doSearch(searchContext, query); } catch (Exception e) { throw new SearchException(e); } }
From source file:com.liferay.document.library.repository.cmis.internal.CMISRepository.java
License:Open Source License
protected Hits doSearch(SearchContext searchContext, Query query) throws Exception { long startTime = System.currentTimeMillis(); Session session = getSession();/* www.jav a 2 s. c om*/ RepositoryInfo repositoryInfo = session.getRepositoryInfo(); RepositoryCapabilities repositoryCapabilities = repositoryInfo.getCapabilities(); QueryConfig queryConfig = searchContext.getQueryConfig(); CapabilityQuery capabilityQuery = repositoryCapabilities.getQueryCapability(); queryConfig.setAttribute("capabilityQuery", capabilityQuery.value()); String productName = repositoryInfo.getProductName(); String productVersion = repositoryInfo.getProductVersion(); queryConfig.setAttribute("repositoryProductName", productName); queryConfig.setAttribute("repositoryProductVersion", productVersion); String queryString = _cmisSearchQueryBuilder.buildQuery(searchContext, query); if (_cmisRepositoryDetector.isNuxeo5_4()) { queryString += " AND (" + PropertyIds.IS_LATEST_VERSION + " = true)"; } if (_log.isDebugEnabled()) { _log.debug("CMIS search query: " + queryString); } boolean searchAllVersions = _cmisRepositoryDetector.isNuxeo5_5OrHigher(); ItemIterable<QueryResult> queryResults = session.query(queryString, searchAllVersions); int start = searchContext.getStart(); int end = searchContext.getEnd(); if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) { start = 0; } int total = 0; List<com.liferay.portal.kernel.search.Document> documents = new ArrayList<>(); List<String> snippets = new ArrayList<>(); List<Float> scores = new ArrayList<>(); for (QueryResult queryResult : queryResults) { total++; if (total <= start) { continue; } if ((total > end) && (end != QueryUtil.ALL_POS)) { continue; } com.liferay.portal.kernel.search.Document document = new DocumentImpl(); String objectId = queryResult.getPropertyValueByQueryName(PropertyIds.OBJECT_ID); if (_log.isDebugEnabled()) { _log.debug("Search result object ID " + objectId); } FileEntry fileEntry = null; try { fileEntry = toFileEntry(objectId, true); } catch (Exception e) { if (_log.isDebugEnabled()) { Throwable cause = e.getCause(); if (cause != null) { cause = cause.getCause(); } if (cause instanceof CmisObjectNotFoundException) { _log.debug("Search result ignored for CMIS document which " + "has a version with an invalid object ID " + cause.getMessage()); } else { _log.debug("Search result ignored for invalid object ID", e); } } total--; continue; } DocumentHelper documentHelper = new DocumentHelper(document); documentHelper.setEntryKey(fileEntry.getModelClassName(), fileEntry.getFileEntryId()); document.addKeyword(Field.TITLE, fileEntry.getTitle()); documents.add(document); if (queryConfig.isScoreEnabled()) { Object scoreObj = queryResult.getPropertyValueByQueryName("HITS"); if (scoreObj != null) { scores.add(Float.valueOf(scoreObj.toString())); } else { scores.add(1.0F); } } else { scores.add(1.0F); } snippets.add(StringPool.BLANK); } float searchTime = (float) (System.currentTimeMillis() - startTime) / Time.SECOND; Hits hits = new HitsImpl(); hits.setDocs(documents.toArray(new com.liferay.portal.kernel.search.Document[documents.size()])); hits.setLength(total); hits.setQuery(query); hits.setQueryTerms(new String[0]); hits.setScores(ArrayUtil.toFloatArray(scores)); hits.setSearchTime(searchTime); hits.setSnippets(snippets.toArray(new String[snippets.size()])); hits.setStart(startTime); return hits; }