Example usage for org.apache.solr.common.params CommonParams Q

List of usage examples for org.apache.solr.common.params CommonParams Q

Introduction

In this page you can find the example usage for org.apache.solr.common.params CommonParams Q.

Prototype

String Q

To view the source code for org.apache.solr.common.params CommonParams Q.

Click Source Link

Document

query string

Usage

From source file:org.alfresco.solr.component.QueryLoggingComponent.java

License:Open Source License

private void log(ResponseBuilder rb) throws IOException {
    boolean isShard = rb.req.getParams().getBool(ShardParams.IS_SHARD, false);
    if (!isShard) {
        CoreContainer container = rb.req.getCore().getCoreContainer();
        SolrCore logCore = container.getCore(rb.req.getCore().getName() + "_qlog");
        if (logCore != null) {
            JSONObject json = (JSONObject) rb.req.getContext().get(AbstractQParser.ALFRESCO_JSON);

            SolrQueryRequest request = null;
            UpdateRequestProcessor processor = null;
            try {
                request = new LocalSolrQueryRequest(logCore, new NamedList<>());
                processor = logCore.getUpdateProcessingChain(null).createProcessor(request,
                        new SolrQueryResponse());

                AddUpdateCommand cmd = new AddUpdateCommand(request);
                cmd.overwrite = true;/* www  .j a  v  a  2  s  . c o m*/
                SolrInputDocument input = new SolrInputDocument();
                input.addField("id", GUID.generate());
                input.addField("_version_", "1");

                input.addField("timestamp", DateTimeFormatter.ISO_INSTANT.format(Instant.now()));

                if (json != null) {
                    try {
                        ArrayList<String> authorityList = new ArrayList<String>(1);
                        JSONArray authorities = json.getJSONArray("authorities");
                        for (int i = 0; i < authorities.length(); i++) {
                            String authorityString = authorities.getString(i);
                            authorityList.add(authorityString);
                        }

                        for (String authority : authorityList) {
                            if (AuthorityType.getAuthorityType(authority) == AuthorityType.USER) {
                                input.addField("user", authority);
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        input.addField("user", "<UNKNOWN>");
                    }
                } else {
                    input.addField("user", "<UNKNOWN>");
                }

                String userQuery = rb.req.getParams().get(SpellingParams.SPELLCHECK_Q);
                if (userQuery == null) {
                    if (json != null) {
                        try {
                            userQuery = json.getString("query");
                        } catch (JSONException e) {
                        }
                    }
                }
                if (userQuery == null) {
                    userQuery = rb.req.getParams().get(CommonParams.Q);
                }

                if (userQuery != null) {
                    input.addField("user_query", userQuery);
                }

                Query query = rb.getQuery();
                input.addField("query", query.toString());

                if (rb.getResults().docList != null) {
                    input.addField("found", rb.getResults().docList.matches());
                }
                input.addField("time", rb.req.getRequestTimer().getTime());

                cmd.solrDoc = input;
                processor.processAdd(cmd);
            }

            finally {
                if (processor != null) {
                    processor.finish();
                }
                if (request != null) {
                    request.close();
                }
            }
        }
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w  w  w . j av a 2s . c  o m
public void addFTSStatusCounts(NamedList<Object> report) {
    try (SolrQueryRequest request = newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, "*:*")
                .set(CommonParams.ROWS, 0).set(FacetParams.FACET, true)
                .set(FacetParams.FACET_FIELD, FIELD_FTSSTATUS);

        SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
        NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
        NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
        NamedList<Integer> ftsStatusCounts = (NamedList) facetFields.get(FIELD_FTSSTATUS);

        long cleanCount = this.getSafeCount(ftsStatusCounts, FTSStatus.Clean.toString());
        report.add("Node count with FTSStatus Clean", cleanCount);

        long dirtyCount = this.getSafeCount(ftsStatusCounts, FTSStatus.Dirty.toString());
        report.add("Node count with FTSStatus Dirty", dirtyCount);

        long newCount = this.getSafeCount(ftsStatusCounts, FTSStatus.New.toString());
        report.add("Node count with FTSStatus New", newCount);
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

@Override
public long getIndexCap() {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams())
                .set(CommonParams.Q, FIELD_SOLR4_ID + ":" + INDEX_CAP_ID).set(CommonParams.ROWS, 1)
                .set(CommonParams.FL, FIELD_DBID);

        SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);

        return docs.stream().findFirst().map(doc -> getFieldValueLong(doc, FIELD_DBID)).map(Math::abs)
                .orElse(-1L);/*from  www.  ja v  a 2  s. c o m*/
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

private void doUpdateDescendantDocs(NodeMetaData parentNodeMetaData, boolean overwrite,
        SolrQueryRequest request, UpdateRequestProcessor processor, LinkedHashSet<Long> stack)
        throws AuthenticationException, IOException, JSONException {

    // skipDescendantDocsForSpecificAspects is initialised on a synchronised method, so access must be also synchronised 
    synchronized (this) {
        if ((skipDescendantDocsForSpecificTypes
                && typesForSkippingDescendantDocs.contains(parentNodeMetaData.getType()))
                || (skipDescendantDocsForSpecificAspects
                        && shouldBeIgnoredByAnyAspect(parentNodeMetaData.getAspects()))) {
            return;
        }// w w  w  . ja  v a2s . c o m
    }

    Set<Long> childIds = new HashSet<>();

    if (parentNodeMetaData.getChildIds() != null) {
        childIds.addAll(parentNodeMetaData.getChildIds());
    }

    String query = FIELD_PARENT + ":\"" + parentNodeMetaData.getNodeRef() + "\"";
    ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
            .set(CommonParams.FL, FIELD_SOLR4_ID);

    if (skippingDocsQueryString != null && !skippingDocsQueryString.isEmpty()) {
        params.set(CommonParams.FQ, "NOT ( " + skippingDocsQueryString + " )");
    }

    SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);
    for (SolrDocument doc : docs) {
        String id = getFieldValueString(doc, FIELD_SOLR4_ID);
        TenantAclIdDbId ids = AlfrescoSolrDataModel.decodeNodeDocumentId(id);
        childIds.add(ids.dbId);
    }

    for (Long childId : childIds) {
        NodeMetaDataParameters nmdp = new NodeMetaDataParameters();
        nmdp.setFromNodeId(childId);
        nmdp.setToNodeId(childId);
        nmdp.setIncludeAclId(false);
        nmdp.setIncludeAspects(false);
        nmdp.setIncludeChildAssociations(false);
        nmdp.setIncludeChildIds(true);
        nmdp.setIncludeNodeRef(false);
        nmdp.setIncludeOwner(false);
        nmdp.setIncludeParentAssociations(false);
        // We only care about the path and ancestors (which is included) for this case
        nmdp.setIncludePaths(true);
        nmdp.setIncludeProperties(false);
        nmdp.setIncludeType(false);
        nmdp.setIncludeTxnId(false);
        // Gets only one
        List<NodeMetaData> nodeMetaDatas = repositoryClient.getNodesMetaData(nmdp, 1);

        if (!nodeMetaDatas.isEmpty()) {
            NodeMetaData nodeMetaData = nodeMetaDatas.get(0);
            if (mayHaveChildren(nodeMetaData)) {
                updateDescendantDocs(nodeMetaData, overwrite, request, processor, stack);
            }

            try {
                lock(childId);

                LOGGER.debug("Cascade update child doc {}", childId);

                // Gets the document that we have from the content store and updates it
                String fixedTenantDomain = AlfrescoSolrDataModel.getTenantId(nodeMetaData.getTenantDomain());
                SolrInputDocument cachedDoc = solrContentStore
                        .retrieveDocFromSolrContentStore(fixedTenantDomain, nodeMetaData.getId());

                if (cachedDoc != null) {
                    updatePathRelatedFields(nodeMetaData, cachedDoc);
                    updateNamePathRelatedFields(nodeMetaData, cachedDoc);
                    updateAncestorRelatedFields(nodeMetaData, cachedDoc);

                    AddUpdateCommand addDocCmd = new AddUpdateCommand(request);
                    addDocCmd.overwrite = overwrite;
                    addDocCmd.solrDoc = cachedDoc;

                    processor.processAdd(addDocCmd);
                    solrContentStore.storeDocOnSolrContentStore(fixedTenantDomain, nodeMetaData.getId(),
                            cachedDoc);
                } else {
                    LOGGER.debug("No child doc found to update {}", childId);
                }
            } finally {
                unlock(childId);
            }
        }
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

private long topNodeId(String sortDir) {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams())
                .set(CommonParams.Q, FIELD_DOC_TYPE + ":" + DOC_TYPE_NODE).set(CommonParams.ROWS, 1)
                .set(CommonParams.SORT, FIELD_DBID + " " + sortDir).set(CommonParams.FL, FIELD_DBID);

        SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);
        return docs.stream().findFirst().map(doc -> getFieldValueLong(doc, FIELD_DBID)).orElse(0L);
    }//from w w w.  j av a  2s . c o m
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private NamedList<Integer> getFacets(SolrQueryRequest request, String query, String field, int minCount) {
    ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
            .set(CommonParams.ROWS, 0).set(FacetParams.FACET, true).set(FacetParams.FACET_FIELD, field)
            .set(FacetParams.FACET_MINCOUNT, minCount);

    SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
    NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
    NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
    return (NamedList) facetFields.get(field);
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

private int getDocListSize(String query) {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
                .set(CommonParams.ROWS, 0);
        ResultContext resultContext = cloud.getResultContext(nativeRequestHandler, request, params);
        return resultContext.getDocList().matches();
    }/*from   w  ww .j  ava2 s  .  c  om*/
}

From source file:org.alfresco.solr.tracker.CascadeTrackerTest.java

License:Open Source License

/**
 * After updating the test data hierarchy (folders and file), the test checks that the cascade tracker properly
 * reflects the changes in the index./*  w  w w . j a  v a2s  .  c o  m*/
 */
@Test
public void solrTracking_folderUpdate_shouldReIndexFolderAndChildren() throws Exception {
    // Update the folder
    Transaction txn = getTransaction(0, 1);

    folderMetaData.getProperties().put(ContentModel.PROP_CASCADE_TX,
            new StringPropertyValue(Long.toString(txn.getId())));
    folderMetaData.getProperties().put(ContentModel.PROP_NAME, new StringPropertyValue("folder2"));
    folderNode.setTxnId(txn.getId());
    folderMetaData.setTxnId(txn.getId());

    // Change the ancestor on the file just to see if it's been updated
    NodeRef nodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
    childFolderMetaData.setAncestors(ancestors(nodeRef));
    fileMetaData.setAncestors(ancestors(nodeRef));

    upsertData(txn, singletonList(folderNode), singletonList(folderMetaData));

    // Check that the ancestor has been changed and indexed
    TermQuery query = new TermQuery(new Term(QueryConstants.FIELD_ANCESTOR, nodeRef.toString()));
    waitForDocCount(query, 2, MAX_WAIT_TIME);

    // Child folder and grandchild document must be updated
    // This is the same query as before but instead of using a Lucene query, it uses the /afts endpoint (request handler)
    ModifiableSolrParams params = new ModifiableSolrParams()
            .add(CommonParams.Q, QueryConstants.FIELD_ANCESTOR + ":\"" + nodeRef.toString() + "\"")
            .add(CommonParams.QT, "/afts").add(CommonParams.START, "0").add(CommonParams.ROWS, "6")
            .add(CommonParams.SORT, "id asc").add(CommonParams.FQ, "{!afts}AUTHORITY_FILTER_FROM_JSON");

    SolrServletRequest req = areq(params,
            "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [ \"mike\"], \"tenants\": [ \"\" ]}");

    assertQ(req, "*[count(//doc)=2]", "//result/doc[1]/long[@name='DBID'][.='" + childFolderNode.getId() + "']",
            "//result/doc[2]/long[@name='DBID'][.='" + fileNode.getId() + "']");
}

From source file:org.apache.blur.slur.BlurQueryHelper.java

License:Apache License

public static BlurQuery from(SolrParams p) {
    BlurQuery blurQuery = new BlurQuery();

    Query query = new Query();
    query.setRowQuery(false);/* w  ww . j av  a  2 s . c  o m*/

    maybeAddSelector(blurQuery, p);

    query.setQuery(p.get(CommonParams.Q));

    blurQuery.setQuery(query);
    return blurQuery;
}

From source file:org.apache.gora.solr.query.SolrResult.java

License:Apache License

public SolrResult(DataStore<K, T> dataStore, Query<K, T> query, SolrServer server, int resultsSize)
        throws IOException {
    super(dataStore, query);
    store = (SolrStore<K, T>) dataStore;
    ModifiableSolrParams params = new ModifiableSolrParams();
    if (query instanceof PartitionQueryImpl) {
        query = ((PartitionQueryImpl<K, T>) query).getBaseQuery();
    }/*from  w  w  w  . ja v a2  s. co m*/
    String q = ((SolrQuery<K, T>) query).toSolrQuery();
    params.set(CommonParams.Q, q);
    fields = query.getFields();
    if (fields == null) {
        params.set(CommonParams.FL, "*");
    } else {
        HashSet<String> uniqFields = new HashSet<String>(Arrays.asList(fields));
        String keyFld = ((SolrStore<K, T>) dataStore).getMapping().getPrimaryKey();
        uniqFields.add(keyFld); // return also primary key
        StringBuilder sb = new StringBuilder();
        for (String f : uniqFields) {
            if (sb.length() > 0)
                sb.append(',');
            sb.append(f);
        }
        params.set(CommonParams.FL, sb.toString());
    }
    params.set(CommonParams.ROWS, resultsSize);
    try {
        QueryResponse rsp = server.query(params);
        list = rsp.getResults();
    } catch (SolrServerException e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}