Example usage for org.apache.solr.client.solrj SolrQuery set

List of usage examples for org.apache.solr.client.solrj SolrQuery set

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery set.

Prototype

public ModifiableSolrParams set(String name, String... val) 

Source Link

Document

Replace any existing parameter with the given name.

Usage

From source file:org.zaizi.sensefy.api.service.SemanticSearchService.java

License:Open Source License

/**
 * Returns a set of relevant documents to an entity or an entity group in
 * input<br>/*from  w  w w . j  a  va 2s  .co  m*/
 * Is possible to search for a specific entity instance, for an entity type
 * and possibly an entity type with some specific attribute<br>
 * This service is called with the information retrieved from the Smart
 * Autocomplete phases.
 * 
 * @param entityId
 *            The unique id for the entity of interest
 * @param entityType
 *            The unique id for the entity type of interest
 * @param entityAttribute
 *            An attribute for the entity type in input eg. nationality for
 *            the entity type: person
 * @param entityAttributeValue
 *            A value of interest for the entity attribute in input eg.
 *            italian for the attribute nationality
 * @param fields
 *            The list of fields to return in the output documents
 * @param filters
 *            A filter query to obtain a subset of the documents relevant to
 *            the main query
 * @param start
 *            The first document to return in the list of relevant documents
 * @param rows
 *            The number of documents to return
 * @param order
 *            The sorting order for the results : <field> <direction> eg:
 *            title_sort desc
 * @param facet
 *            If enabled the relevant results will contain the facet
 *            countings
 * @param security
 *            If enabled the relevant results will be filtered based on user
 *            permissions
 * @param sensefyToken
 *            The Sensefy Token that contains relevant information for the
 *            user running the query
 * @return A json representation of the list of relevant documents for the
 *         input query
 */
public SearchResponse entityDrivenSearch(String entityId, String entityType, String entityAttribute,
        String entityAttributeValue, String fields, String filters, int start, Integer rows, String order,
        boolean facet, boolean security, Principal user, boolean clustering) {
    String stringQuery;
    QueryResponse queryResponse;
    SearchResponse response = new SearchResponse();
    SearchResults responseContent = new SearchResults();
    Long startTime = System.currentTimeMillis();
    try {

        if ((entityType == null || entityType.isEmpty()) && (entityId == null || entityId.isEmpty())) {
            throw new SensefyException(400, "<entityType> or <entityId> param required");
        }

        stringQuery = QueryBuilder.getQueryString(entityId, entityType, entityAttribute, entityAttributeValue,
                response);

        SolrQuery solrQuery = QueryBuilder.getSolrQuery(stringQuery, fields, facet,
                facetConfigurer.getFacetConfiguration(), filters, start, rows, order, security, false,
                clustering, user);
        // retrieve the entity
        SolrDocument extractedEntity = getEntity(entityId);
        responseContent.setEntity(extractedEntity);

        //         // retrieve the entity type
        //         EntityType extractedEntityType = getEntityType(entityType);
        //         responseContent.setEntityType(extractedEntityType);

        String labelVal = (String) extractedEntity.getFieldValue(ENTITY_DRIVEN_HIGHLIGH_FIELD);
        logger.debug("Entity label for the entity driven search : " + labelVal);
        solrQuery.set(ENTITY_DRIVEN_HIGHLIGH_QUERY_PARAM, labelVal);
        queryResponse = this.getPrimaryIndex().query(solrQuery);
        //get the highlights
        Map<String, Map<String, List<String>>> highlightingSnippets = queryResponse.getHighlighting();

        SolrDocumentList docsRetrievedFromEntity = queryResponse.getResults();
        FacetParser.parseFacets(queryResponse, response, facetConfigurer.getFacetConfiguration());
        responseContent.setStart(start);
        responseContent.setNumFound(docsRetrievedFromEntity.getNumFound());
        responseContent.setDocuments(docsRetrievedFromEntity);
        responseContent.setHighlight(highlightingSnippets);

        response.setSearchResults(responseContent);
    } catch (SensefyException e) {
        processAPIException(response, e, "[Entity Driven Search] Error - stacktrace follows", 400,
                ComponentCode.QUERY);
    } catch (SolrServerException e) {
        processAPIException(response, e, "[Entity Driven Search] Error - stacktrace follows", 500,
                ComponentCode.SOLR);
    }

    Long elapsedTime = System.currentTimeMillis() - startTime;
    response.setTime(elapsedTime);
    return response;
}

From source file:org.zaizi.sensefy.api.service.SemanticSearchService.java

License:Open Source License

/**
 * Get an Entity from the EntityCore using the Solr GET on that core
 *
 * @param entityId/*  w w  w .j  a va 2s .c om*/
 * @return
 * @throws org.apache.solr.client.solrj.SolrServerException
 */
private SolrDocument getEntity(String entityId) throws SolrServerException {
    SolrDocument extractedEntity = null;
    if (entityId != null && !entityId.isEmpty()) {
        SolrQuery entityQuery = new SolrQuery();
        entityQuery.setRequestHandler("/get");
        entityQuery.set("ids", entityId);
        QueryResponse entityResponse;
        entityResponse = this.getEntityCore().query(entityQuery);
        List<SolrDocument> entities = entityResponse.getResults();
        if (entities.size() > 0) {
            extractedEntity = entities.get(0);
        }
    }
    return extractedEntity;
}

From source file:org.zaizi.sensefy.api.service.SolrSmartAutoCompleteService.java

License:Open Source License

/**
 * This method return the shingle suggestions for the term the query the
 * user is typing/*w  w  w  . j  a  v  a 2 s  .  co m*/
 *
 * @param numberOfSuggestions
 * @param termToComplete
 * @param primaryIndex
 * @return
 */
private List<String> getShingleSuggestions(Integer numberOfSuggestions, String termToComplete,
        SolrServer primaryIndex) throws SolrServerException, SolrException, IOException {
    List<String> shingleSuggestions = new ArrayList<String>();
    SolrQuery shingleSuggestionQuery = new SolrQuery(termToComplete);
    shingleSuggestionQuery.setRequestHandler("/autocomplete");
    shingleSuggestionQuery.set("suggest.count", numberOfSuggestions);
    QueryResponse shingleTitleSuggestionResponse;
    shingleTitleSuggestionResponse = primaryIndex.query(shingleSuggestionQuery);
    shingleSuggestions = parseSuggestionsFromJson(termToComplete, shingleTitleSuggestionResponse);
    return shingleSuggestions;
}

From source file:org.zaizi.sensefy.api.solr.querybuilder.QueryBuilder.java

License:Open Source License

/**
 * return a solr query built with all the parameters in input . Spellcheck
 * included/*from  ww  w . ja v a  2 s.c o  m*/
 * 
 * @param query
 * @param fields
 * @param filters
 * @param start
 * @param rows
 * @param security
 * @param clustering
 * @param sensefyToken
 * @return
 * @throws SensefyException
 */
public static SolrQuery getSolrQuery(String query, String fields, boolean facet,
        FacetConfigurationList facetConfig, String filters, int start, Integer rows, String order,
        boolean security, boolean spellcheck, boolean clustering, Principal user) {

    SensefyUser sensefyUser = SensefyUserMapper.getSensefyUserFromPrincipal(user);

    if (rows == null) {
        rows = DEFAULT_ROWS;
    }
    // retrieve the documents from primary index
    SolrQuery documentsQuery = new SolrQuery(query);
    Set<String> selectedFields = new HashSet<String>();
    documentsQuery.setRows(rows);
    documentsQuery.set("spellcheck", spellcheck);
    documentsQuery.set("clustering", clustering);
    if (fields != null && !fields.isEmpty()) {
        String[] fieldsArray = fields.split(",");
        documentsQuery.setFields(fieldsArray);
    }
    if (filters != null && !filters.isEmpty()) {
        String[] filtersArray = buildFilterQueries(filters.split(","), selectedFields);
        documentsQuery.setFilterQueries(filtersArray);
    }
    if (order != null && !order.isEmpty()) {
        documentsQuery.set(CommonParams.SORT, order);
    }

    if (security) {

        String filterQueryACLs = SecurityQueryBuilder.getSecurityFilterQuery(sensefyUser);
        documentsQuery.addFilterQuery(filterQueryACLs);

    }
    documentsQuery.set("TZ", sensefyUser.getTimezone().getID());
    documentsQuery.setStart(start);
    ModifiableSolrParams querySolrParams = new ModifiableSolrParams();
    if (facet) {
        // facets must be created with proper exclusion tag where needed
        documentsQuery.setFacet(true);
        List<FacetConfiguration> facetConfigurations = facetConfig.getFacetConfigurations();
        for (FacetConfiguration facetConfiguration : facetConfigurations) {
            String tag = null;
            if (selectedFields.contains(facetConfiguration.getField()))
                tag = "tag-" + facetConfiguration.getField();
            facetConfiguration.getSolrFacetParams(querySolrParams, tag);
        }
    }
    documentsQuery.add(querySolrParams);
    return documentsQuery;
}

From source file:peltomaa.sukija.Query.java

License:Open Source License

public void query(String text) {
    try {/*w  w w  .  j  av  a  2s  . co  m*/
        SolrQuery query = new SolrQuery();
        query.setQuery(text);
        query.setParam("rows", "1000");
        query.addTermsField("text");
        query.setTerms(true);
        query.setParam("hl.useFastVectorHighlighter", "true");
        query.setParam("hl.mergeContiguous", "true");
        //    query.setParam ("hl.fragsize", "0");
        query.setParam("hl.maxAnalyzedChars", "-1");

        // To choose a different request handler, for example, just set the qt parameter.
        query.set("qt", "/sukija");
        QueryResponse response = server.query(query);

        //    for (String s : query.getTermsFields()) System.out.println ("Field " + s);
        //    QueryResponsePrinter.print (System.out, response);

        SolrDocumentList documents = response.getResults();

        if (documents == null) {
            messageField.setText("Sukija.java: documents == null: ohjelmassa on virhe.");
            System.exit(1);
        }

        setMessage(documents.size());

        if (documents.size() == 0) {
            editorPane.setText("");
        } else {
            editorPane.setText(getText(response));
            editorPane.setCaretPosition(0);
        }
    } catch (SolrServerException ex) {
        messageField.setText(ex.getMessage());
    } catch (Exception ex) {
        messageField.setText(ex.getMessage());
    }
}

From source file:richtercloud.solr.bean.indexing.NewMain.java

/**
 * @param args the command line arguments
 *///from  w  w  w . ja  v  a 2 s.co  m
public static void main(String[] args) {
    SolrClient solrServer;
    solrServer = new HttpSolrClient.Builder("http://localhost:8983/solr/test1").build();
    List<MyBean> myBeans = new LinkedList<>(
            Arrays.asList(new MyBean("a", "1", 1), new MyBean("b", "2", 2), new MyBean("c", "3", 3)));
    String searchTerm = "a";
    try {
        solrServer.addBeans(myBeans);
        solrServer.commit();
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q", searchTerm);
        QueryResponse queryResponse = solrServer.query(solrQuery);
        List<MyBean> foundDocuments = queryResponse.getBeans(MyBean.class);
        System.out.println(foundDocuments);
    } catch (SolrServerException | IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:ru.org.linux.search.SearchViewer.java

License:Apache License

public QueryResponse performSearch(SolrServer search) throws SolrServerException {
    SolrQuery params = new SolrQuery();
    // set search query params
    params.set("q", query.getQ());
    params.set("rows", SEARCH_ROWS);
    params.set("start", query.getOffset());

    params.set("qt", "edismax");

    if (query.getRange().getParam() != null) {
        params.add("fq", query.getRange().getParam());
    }/*w w  w .j a va 2 s  .com*/

    if (query.getInterval().getRange() != null) {
        params.add("fq", query.getInterval().getRange());
    }

    params.setFacetMinCount(1);
    params.setFacet(true);

    String section = query.getSection();

    if (section != null && !section.isEmpty() && !"0".equals(section)) {
        params.add("fq", "{!tag=dt}section:" + query.getSection());
        params.addFacetField("{!ex=dt}section");

        params.addFacetField("{!ex=dt}group_id");
    } else {
        params.addFacetField("section");
        params.addFacetField("group_id");
    }

    if (query.getUser() != null) {
        User user = query.getUser();

        if (query.isUsertopic()) {
            params.add("fq", "topic_user_id:" + user.getId());
        } else {
            params.add("fq", "user_id:" + user.getId());
        }
    }

    if (query.getGroup() != 0) {
        params.add("fq", "{!tag=dt}group_id:" + query.getGroup());
    }

    params.set("sort", query.getSort().getParam());

    return search.query(params);
}

From source file:se.kmr.scam.sqi.query.ScamRepositoryQueryManagerImpl.java

License:Apache License

/**
 * Search in the repository after entries
 * //from w w w .j ava2 s .c  o m
 * @param query a query of format {@link #getLanguage()}.
 * @param start start record of the results set. The index of the result set size starts with 1.
  * @param resultsSetSize number of results.  0 (zero) = no limit
  * @param maxResults maximum number of query results.  0 (zero) = no limit
 * @param resultsFormat format of the results
 *
 * @return A string with hits or null.
 * @throws Exception if something goes wrong
 */
public String query(String query, int start, int resultsSetSize, int maxResults, ResultFormatType resultsFormat)
        throws TranslationException {
    log.info("query:from= " + getLanguage().toString() + "\nto= " + QueryLanguageType.LUCENEQL.toString()
            + "\nresultsFormat= " + resultsFormat.toString() + "\nquery= " + query);

    //List<Entry> searchResults = sparqlSearch(query);
    SolrQuery q = new SolrQuery(query);
    q.set("public", "true");
    q.setStart(start);
    q.setRows(resultsSetSize);
    q.addSortField("score", ORDER.desc);
    q.addSortField("modified", ORDER.desc);
    QueryResult r = rm.getSolrSupport().sendQuery(q);
    Set<Entry> searchResults = r.getEntries();
    resultCount.put(query, r.getHits());
    String searchResult = null;

    if (resultsFormat == ResultFormatType.LOM) {
        searchResult = createResultsLOM(new ArrayList<Entry>(searchResults), start, resultsSetSize, maxResults);
    } else if (resultsFormat == ResultFormatType.STRICT_LRE) {
        searchResult = createResultsStrictLRE(new ArrayList<Entry>(searchResults), start, resultsSetSize,
                maxResults);
    } else if (resultsFormat == ResultFormatType.PLRF0) {
        searchResult = createResultsPLRF0(new ArrayList<Entry>(searchResults), start, resultsSetSize,
                maxResults);
    }

    return searchResult;
}

From source file:se.kmr.scam.sqi.query.ScamRepositoryQueryManagerImpl.java

License:Apache License

/**
 * count returns the total number for matching metadata records found by query
 * //from  ww  w . j a  v  a  2s .  c o  m
 * @param query a query of format {@link #getLanguage()}. 
 * 
 * @return nr of hits
 */
public int count(String query) throws TranslationException {
    log.info("count:query= " + query);
    Long count = null;
    if (resultCount.containsKey(query)) {
        count = resultCount.get(query);
    }
    if (count != null) {
        return count.intValue();
    }

    SolrQuery q = new SolrQuery(query);
    q.set("public", "true");
    QueryResult r = rm.getSolrSupport().sendQuery(q);
    count = r.getHits();
    resultCount.put(query, count);

    return count.intValue();
}

From source file:se.uu.ub.cora.solrsearch.SolrRecordSearch.java

License:Open Source License

private void createQueryForLinkedData(SolrQuery solrQuery, DataAtomic childElementFromSearchAsAtomic,
        DataGroup searchTerm, String indexFieldName) {
    String linkedOnIndexFieldName = getLinkedOnIndexFieldNameFromStorageUsingSearchTerm(searchTerm);
    String query = "{!join from=ids to=" + linkedOnIndexFieldName + "}" + indexFieldName + ":"
            + childElementFromSearchAsAtomic.getValue();
    query += " AND type:" + searchTerm.getFirstGroupWithNameInData("searchInRecordType")
            .getFirstAtomicValueWithNameInData(LINKED_RECORD_ID);
    solrQuery.set("q", query);
}