Search in sources :

Example 16 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchMapperTests method fromQuery.

@Test
public void fromQuery() throws Exception {
    SearchParameters searchParameters = new SearchParameters();
    try {
        searchMapper.fromQuery(searchParameters, new Query(null, null, null));
        fail();
    } catch (IllegalArgumentException iae) {
        assertTrue(iae.getLocalizedMessage().contains("query is a mandatory parameter"));
    }
    Query q = new Query(null, "hello", null);
    searchMapper.fromQuery(searchParameters, q);
    // Default
    assertEquals(LANGUAGE_FTS_ALFRESCO, searchParameters.getLanguage());
    q = new Query("world", "hello", null);
    try {
        searchMapper.fromQuery(searchParameters, q);
        fail();
    } catch (InvalidArgumentException iae) {
        assertNotNull(iae);
    // world is not a valid language type
    }
    q = new Query("afts", "hello", null);
    searchMapper.fromQuery(searchParameters, q);
    assertEquals(LANGUAGE_FTS_ALFRESCO, searchParameters.getLanguage());
    q = new Query("cMiS", "hello", null);
    searchMapper.fromQuery(searchParameters, q);
    assertEquals(LANGUAGE_CMIS_ALFRESCO, searchParameters.getLanguage());
    q = new Query("LuCENE", "hello", null);
    searchMapper.fromQuery(searchParameters, q);
    assertEquals(LANGUAGE_LUCENE, searchParameters.getLanguage());
    assertEquals("hello", searchParameters.getQuery());
    q = new Query("LuCENE", "hello", "Heload");
    searchMapper.fromQuery(searchParameters, q);
    assertEquals("Heload", searchParameters.getSearchTerm());
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) FacetQuery(org.alfresco.rest.api.search.model.FacetQuery) FilterQuery(org.alfresco.rest.api.search.model.FilterQuery) Query(org.alfresco.rest.api.search.model.Query) SearchQuery(org.alfresco.rest.api.search.model.SearchQuery) Test(org.junit.Test)

Example 17 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchSQLApiWebscriptTests method testSearchQueryParams.

@Test
public void testSearchQueryParams() throws Exception {
    String query = "select SITE from alfresco";
    SearchSQLQuery searchQuery = new SearchSQLQuery(query, "solr", Collections.emptyList(), 1000);
    SearchParameters sparams = webscript.buildSearchParameters(searchQuery);
    assertNotNull(sparams);
    assertEquals(query, sparams.getQuery());
    assertEquals(Collections.EMPTY_LIST, sparams.getLocales());
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) SearchSQLQuery(org.alfresco.rest.api.search.model.SearchSQLQuery) Test(org.junit.Test)

Example 18 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchMapper method fromFacetIntervals.

/**
 * Sets the Interval Parameters object on search parameters
 *
 * It does some valiation then takes any "SETS" at the top level and sets them at every field level.
 *
 * @param sp SearchParameters
 * @param facetIntervals IntervalParameters
 */
public void fromFacetIntervals(SearchParameters sp, IntervalParameters facetIntervals) {
    if (facetIntervals != null) {
        ParameterCheck.mandatory("facetIntervals intervals", facetIntervals.getIntervals());
        Set<IntervalSet> globalSets = facetIntervals.getSets();
        validateSets(globalSets, "facetIntervals");
        if (facetIntervals.getIntervals() != null && !facetIntervals.getIntervals().isEmpty()) {
            List<String> intervalLabels = new ArrayList<>(facetIntervals.getIntervals().size());
            for (Interval interval : facetIntervals.getIntervals()) {
                ParameterCheck.mandatory("facetIntervals intervals field", interval.getField());
                validateSets(interval.getSets(), "facetIntervals intervals " + interval.getField());
                if (interval.getSets() != null && globalSets != null) {
                    interval.getSets().addAll(globalSets);
                }
                ParameterCheck.mandatoryCollection("facetIntervals intervals sets", interval.getSets());
                List<Map.Entry<String, Long>> duplicateSetLabels = interval.getSets().stream().collect(groupingBy(IntervalSet::getLabel, Collectors.counting())).entrySet().stream().filter(e -> e.getValue().intValue() > 1).collect(toList());
                if (!duplicateSetLabels.isEmpty()) {
                    throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID, new Object[] { ": duplicate set interval label " + duplicateSetLabels.toString() });
                }
                if (interval.getLabel() != null)
                    intervalLabels.add(interval.getLabel());
            }
            List<Map.Entry<String, Long>> duplicateIntervalLabels = intervalLabels.stream().collect(groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().filter(e -> e.getValue().intValue() > 1).collect(toList());
            if (!duplicateIntervalLabels.isEmpty()) {
                throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID, new Object[] { ": duplicate interval label " + duplicateIntervalLabels.toString() });
            }
        }
        if (facetIntervals.getSets() != null) {
            facetIntervals.getSets().clear();
        }
    }
    sp.setInterval(facetIntervals);
}
Also used : Arrays(java.util.Arrays) FacetQuery(org.alfresco.rest.api.search.model.FacetQuery) Pivot(org.alfresco.rest.api.search.model.Pivot) Paging(org.alfresco.rest.framework.resource.parameters.Paging) PARAM_INCLUDE_PROPERTIES(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_PROPERTIES) RangeParameters(org.alfresco.service.cmr.search.RangeParameters) Template(org.alfresco.rest.api.search.model.Template) IntervalParameters(org.alfresco.service.cmr.search.IntervalParameters) Limits(org.alfresco.rest.api.search.model.Limits) Matcher(java.util.regex.Matcher) Params(org.alfresco.rest.framework.resource.parameters.Params) Locale(java.util.Locale) Map(java.util.Map) LANGUAGE_FTS_ALFRESCO(org.alfresco.service.cmr.search.SearchService.LANGUAGE_FTS_ALFRESCO) Scope(org.alfresco.rest.api.search.model.Scope) PARAM_INCLUDE_PATH(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_PATH) Localization(org.alfresco.rest.api.search.model.Localization) TimeZone(java.util.TimeZone) Set(java.util.Set) FacetFields(org.alfresco.rest.api.search.model.FacetFields) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) IntervalSet(org.alfresco.service.cmr.search.IntervalSet) List(java.util.List) LuceneQueryLanguageSPI(org.alfresco.repo.search.impl.lucene.LuceneQueryLanguageSPI) PARAM_INCLUDE_ALLOWABLEOPERATIONS(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_ALLOWABLEOPERATIONS) Optional(java.util.Optional) Default(org.alfresco.rest.api.search.model.Default) FilterQuery(org.alfresco.rest.api.search.model.FilterQuery) SortDef(org.alfresco.rest.api.search.model.SortDef) LimitBy(org.alfresco.service.cmr.search.LimitBy) PARAM_INCLUDE_ISLINK(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_ISLINK) Interval(org.alfresco.service.cmr.search.Interval) FieldFacet(org.alfresco.service.cmr.search.SearchParameters.FieldFacet) SearchRequestContext(org.alfresco.rest.api.search.context.SearchRequestContext) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) GeneralHighlightParameters(org.alfresco.service.cmr.search.GeneralHighlightParameters) Function(java.util.function.Function) ArrayList(java.util.ArrayList) FieldFacetSort(org.alfresco.service.cmr.search.SearchParameters.FieldFacetSort) PARAM_INCLUDE_ASPECTNAMES(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_ASPECTNAMES) ParameterCheck(org.alfresco.util.ParameterCheck) StatsRequestParameters(org.alfresco.service.cmr.search.StatsRequestParameters) FacetField(org.alfresco.rest.api.search.model.FacetField) LANGUAGE_LUCENE(org.alfresco.service.cmr.search.SearchService.LANGUAGE_LUCENE) SortType(org.alfresco.service.cmr.search.SearchParameters.SortDefinition.SortType) StoreRef(org.alfresco.service.cmr.repository.StoreRef) PARAM_INCLUDE_ASSOCIATION(org.alfresco.rest.api.Nodes.PARAM_INCLUDE_ASSOCIATION) FieldFacetMethod(org.alfresco.service.cmr.search.SearchParameters.FieldFacetMethod) LANGUAGE_CMIS_ALFRESCO(org.alfresco.service.cmr.search.SearchService.LANGUAGE_CMIS_ALFRESCO) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) Operator(org.alfresco.service.cmr.search.SearchParameters.Operator) Query(org.alfresco.rest.api.search.model.Query) Collectors.toList(java.util.stream.Collectors.toList) SearchQuery(org.alfresco.rest.api.search.model.SearchQuery) SortDefinition(org.alfresco.service.cmr.search.SearchParameters.SortDefinition) Spelling(org.alfresco.rest.api.search.model.Spelling) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) IntervalSet(org.alfresco.service.cmr.search.IntervalSet) ArrayList(java.util.ArrayList) Interval(org.alfresco.service.cmr.search.Interval)

Example 19 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class KeywordSearch method search.

/**
 * Execute the search
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, Locale locale, WebScriptRequest req) {
    SearchResult searchResult = null;
    ResultSet results = null;
    try {
        // construct search statement
        String[] terms = searchTerms.split(" ");
        searchTerms = searchTerms.replaceAll("\"", "&quot;");
        // Escape special characters in the terms, so that they can't confuse the parser
        for (int i = 0; i < terms.length; i++) {
            terms[i] = SearchLanguageConversion.escapeLuceneQuery(terms[i]);
        }
        Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
        statementModel.put("args", createArgs(req));
        statementModel.put("terms", terms);
        Writer queryWriter = new StringWriter(1024);
        renderFormatTemplate(QUERY_FORMAT, statementModel, queryWriter);
        String query = queryWriter.toString();
        // execute query
        if (logger.isDebugEnabled()) {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage + ", itemsPerPage=" + itemsPerPage + ", search locale=" + locale.toString());
            logger.debug("Issuing lucene search: " + query);
        }
        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(query);
        if (locale != null) {
            parameters.addLocale(locale);
        }
        results = searchService.query(parameters);
        int totalResults = results.length();
        if (logger.isDebugEnabled())
            logger.debug("Results: " + totalResults + " rows (limited: " + results.getResultSetMetaData().getLimitedBy() + ")");
        // are we out-of-range
        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
        if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
            throw new WebScriptException("Start page " + startPage + " is outside boundary of " + totalPages + " pages");
        }
        // construct search result
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0) {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
            searchResult.setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            // Make the search resilient to invalid nodes
            if (!nodeService.exists(node)) {
                continue;
            }
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    } finally {
        if (results != null) {
            results.close();
        }
    }
}
Also used : HashMap(java.util.HashMap) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringWriter(java.io.StringWriter) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) ResultSet(org.alfresco.service.cmr.search.ResultSet) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 20 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class ForumTopicsFilteredGet method doSearch.

/**
 * Do the actual search
 *
 * @param searchQuery Pair with query string in first and query language in second
 * @param sortAscending boolean
 * @param paging PagingRequest
 */
protected PagingResults<TopicInfo> doSearch(Pair<String, String> searchQuery, boolean sortAscending, PagingRequest paging) {
    ResultSet resultSet = null;
    PagingResults<TopicInfo> pagedResults = new EmptyPagingResults<TopicInfo>();
    String sortOn = "@{http://www.alfresco.org/model/content/1.0}created";
    // Setup the search parameters
    SearchParameters sp = new SearchParameters();
    sp.addStore(SPACES_STORE);
    sp.setQuery(searchQuery.getFirst());
    sp.setLanguage(searchQuery.getSecond());
    sp.addSort(sortOn, sortAscending);
    if (paging.getMaxItems() > 0) {
        // Multiply maxItems by 10.  This is to catch topics that have multiple replies and ensure that the maximum number of topics is shown.
        sp.setLimit(paging.getMaxItems() * 10);
        sp.setLimitBy(LimitBy.FINAL_SIZE);
    }
    if (paging.getSkipCount() > 0) {
        sp.setSkipCount(paging.getSkipCount());
    }
    try {
        resultSet = searchService.query(sp);
        pagedResults = wrap(resultSet, paging);
    } finally {
        try {
            resultSet.close();
        } catch (Exception e) {
        // do nothing
        }
    }
    return pagedResults;
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ResultSet(org.alfresco.service.cmr.search.ResultSet) EmptyPagingResults(org.alfresco.query.EmptyPagingResults) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo) WebScriptException(org.springframework.extensions.webscripts.WebScriptException)

Aggregations

SearchParameters (org.alfresco.service.cmr.search.SearchParameters)56 Test (org.junit.Test)28 ResultSet (org.alfresco.service.cmr.search.ResultSet)20 NodeRef (org.alfresco.service.cmr.repository.NodeRef)19 ArrayList (java.util.ArrayList)15 SearchRequestContext (org.alfresco.rest.api.search.context.SearchRequestContext)11 IOException (java.io.IOException)10 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)10 HashMap (java.util.HashMap)8 SearchQuery (org.alfresco.rest.api.search.model.SearchQuery)8 JSONObject (org.json.JSONObject)8 List (java.util.List)7 QName (org.alfresco.service.namespace.QName)7 JSONTokener (org.json.JSONTokener)7 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)6 SearchSQLQuery (org.alfresco.rest.api.search.model.SearchSQLQuery)6 Params (org.alfresco.rest.framework.resource.parameters.Params)6 StoreRef (org.alfresco.service.cmr.repository.StoreRef)6 GeneralHighlightParameters (org.alfresco.service.cmr.search.GeneralHighlightParameters)6 JSONArray (org.json.JSONArray)6