Example usage for org.apache.solr.search QueryParsing V

List of usage examples for org.apache.solr.search QueryParsing V

Introduction

In this page you can find the example usage for org.apache.solr.search QueryParsing V.

Prototype

String V

To view the source code for org.apache.solr.search QueryParsing V.

Click Source Link

Usage

From source file:alba.solr.core.DynamicQueryParser.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {

    postFilters = (Map<String, CallableFunction>) req.getContext().get(Loader.POSTFILTERS);

    cachedResults = (Map<Object, CachedResult>) req.getContext().get(Loader.CACHEDRESULTS);

    CallableFunction function = postFilters.get(localParams.get("name"));

    return new QParser(qstr, localParams, params, req) {

        private ValueSource functionParamValueSource;

        @Override//from  ww  w .j  a  v  a2  s .c  om
        public Query parse() throws SyntaxError {

            ValueSource vs = null;

            Map<String, Object> params = new HashMap<String, Object>();

            String funcStr = localParams.get(QueryParsing.V, null);

            int nParams = 1;

            if ((function != null) && (function.getMethod() != null)) {
                nParams = function.getMethod().getParameterCount();
            }

            boolean cache = false;

            Object functionParams[] = new Object[nParams];

            int i = 1; //in the 0th positions there's the parametric function result (as ValueSource)
            Iterator<String> it = localParams.getParameterNamesIterator();
            while (it.hasNext()) {
                String p = it.next();

                /* does it make sense to be able to switch on/off the cache? what would it imply? 
                if ("cache".equals(p)) {
                   cache = ("1".equals(localParams.get(p)));
                }
                */

                if (!"v".equals(p) && !"cache".equals(p) && !"type".equals(p) && !"name".equals(p)) {
                    params.put(p, localParams.get(p));

                    Class<?> expectedType = function.getMethod().getParameters()[i].getType();
                    if (expectedType == Integer.class) {
                        functionParams[i] = Integer.parseInt(localParams.get(p));
                    } else {
                        logger.error("param " + i + " should be of type " + expectedType
                                + " but I don't know how to parse it.");
                        // right place for magic params? like passing the request & so on.. ?
                    }

                    i++;
                }
            }

            if ((funcStr != null) && (funcStr != "")) {
                Query funcQ = subQuery(funcStr, FunctionQParserPlugin.NAME).getQuery();

                //if (funcQ instanceof FunctionQuery) {  //what else could be?
                vs = ((FunctionQuery) funcQ).getValueSource();
                functionParamValueSource = vs; //todo must call getValues when using it!

            } else {
                logger.error("!!!! no function defined for the postfilter???");
            }

            DynamicQuery dq = new DynamicQuery(vs, cache, function, functionParams, cachedResults);

            dq.setParams(params);

            return dq;
        }
    };
}

From source file:com.alipay.tiansuan.solrplugin.SelectInLocalFileQParserPlugin.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {
        @Override//from   w ww.  ja v a  2 s  .  c om
        public Query parse() throws ParseException {
            try {
                String file = localParams.get(QueryParsing.V);
                String field = localParams.get(QueryParsing.F);

                SchemaField sf = req.getSchema().getField(field);
                FieldType ft = sf.getType();
                if (ft instanceof StrField) {
                    return new StringSelectInQuery<String>(file, field, new HdfsToSet.TransString());
                }
                if (ft instanceof TrieField) {
                    TrieField tft = (TrieField) ft;
                    TrieTypes cdt = tft.getType();
                    if (cdt.equals(TrieTypes.INTEGER)) {
                        return new NumericSelectInQuery<Integer>(field, tft.getPrecisionStep(), DataType.INT,
                                new HdfsToSet.TransInt(), file);
                    }
                    if (cdt.equals(TrieTypes.LONG)) {
                        return new NumericSelectInQuery<Long>(field, tft.getPrecisionStep(), DataType.LONG,
                                new HdfsToSet.TransLong(), file);
                    }

                    if (cdt.equals(TrieTypes.FLOAT)) {
                        return new NumericSelectInQuery<Float>(field, tft.getPrecisionStep(), DataType.FLOAT,
                                new HdfsToSet.TransFloat(), file);
                    }

                    if (cdt.equals(TrieTypes.DOUBLE)) {
                        return new NumericSelectInQuery<Double>(field, tft.getPrecisionStep(), DataType.DOUBLE,
                                new HdfsToSet.TransDouble(), file);
                    }

                    if (cdt.equals(TrieTypes.DATE)) {
                        return new NumericSelectInQuery<Long>(field, tft.getPrecisionStep(), DataType.LONG,
                                new HdfsToSet.TransDate(), file);
                    }
                }

                throw new ParseException("file type error");

            } catch (Exception e) {
                throw new ParseException(e.toString());
            }
        }
    };
}

From source file:com.alipay.tiansuan.solrplugin.StringCotainsQParserPlugin.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {
        @Override//from  w  ww.  ja va  2 s.c  om
        public Query parse() throws ParseException {
            try {
                String contains = localParams.get(QueryParsing.V);
                String field = localParams.get(QueryParsing.F);
                return new StringContainsQuery(contains.split(","), field);

            } catch (Exception e) {
                throw new ParseException(e.toString());
            }
        }
    };
}

From source file:com.ifactory.press.db.solr.search.ScoringParentQParser.java

License:Apache License

@Override
public Query parse() throws SyntaxError {
    if (localParams == null) {
        throw new SyntaxError("join query parser must be invoked using localParams");
    }//from   ww  w  .  j  av  a  2s.c o m
    String filter = localParams.get(getParentFilterLocalParamName());
    QParser parentParser = subQuery(filter, null);
    Query parentQ = parentParser.getQuery();

    String queryText = localParams.get(QueryParsing.V);
    // there is no child query, return parent filter from cache
    if (queryText == null || queryText.length() == 0) {
        SolrConstantScoreQuery wrapped = new SolrConstantScoreQuery(getFilter(parentQ));
        wrapped.setCache(false);
        return wrapped;
    }
    QParser childrenParser = subQuery(queryText, null);
    Query childrenQuery = childrenParser.getQuery();
    return createQuery(parentQ, childrenQuery);
}

From source file:com.kmwllc.search.solr.parser.GraphQueryParser.java

License:Open Source License

@Override
public Query parse() throws SyntaxError {

    SolrParams localParams = getLocalParams();
    SolrParams params = getParams();//from  ww w.  j  a  v a 2  s.c  o m
    SolrParams solrParams = SolrParams.wrapDefaults(localParams, params);
    QParser baseParser = subQuery(solrParams.get(QueryParsing.V), null);
    Query startNodesQuery = baseParser.getQuery();
    String fromField = localParams.get("from", "node_id");
    String toField = localParams.get("to", "edge_ids");

    QParser traversalBaseParser = subQuery(localParams.get("traversalFilter"), null);
    Query traversalFilter = traversalBaseParser.getQuery();

    // TODO: un-invert this logic
    boolean onlyLeafNodes = Boolean.valueOf(localParams.get("returnOnlyLeaf", "false"));
    boolean returnStartNodes = Boolean.valueOf(localParams.get("returnRoot", "true"));
    int maxDepth = Integer.valueOf(localParams.get("maxDepth", "-1"));

    GraphQuery gq = new GraphQuery(startNodesQuery, fromField, toField, traversalFilter);
    gq.setMaxDepth(maxDepth);
    gq.setOnlyLeafNodes(onlyLeafNodes);
    gq.setReturnStartNodes(returnStartNodes);
    return gq;
}

From source file:uk.co.flax.biosolr.builders.AbstractFacetTreeBuilder.java

License:Apache License

@Override
public void initialiseParameters(SolrParams localParams) throws SyntaxError {
    getLogger().trace("Initialising parameters...");
    if (localParams == null) {
        throw new SyntaxError("Missing facet tree parameters");
    }/*from w ww .  j  a  v a 2  s .c  o  m*/

    // Initialise the node field - REQUIRED
    nodeField = localParams.get(FacetTreeParameters.NODE_FIELD_PARAM);
    if (StringUtils.isBlank(nodeField)) {
        // Not specified in localParams - use the key value instead
        nodeField = localParams.get(QueryParsing.V);

        // If still blank, we have a problem
        if (StringUtils.isBlank(nodeField)) {
            throw new SyntaxError("No node field defined in " + localParams);
        }
    }

    //  Initialise the optional fields
    labelField = localParams.get(FacetTreeParameters.LABEL_FIELD_PARAM, null);
}

From source file:uk.co.flax.biosolr.builders.ChildNodeFacetTreeBuilderTest.java

License:Apache License

@Test(expected = org.apache.solr.search.SyntaxError.class)
public void initialiseParameters_missingNodeFieldParam() throws Exception {
    final SolrParams params = mock(SolrParams.class);
    when(params.get(FacetTreeParameters.NODE_FIELD_PARAM)).thenReturn(null);
    when(params.get(QueryParsing.V)).thenReturn(null);

    ChildNodeFacetTreeBuilder ftb = new ChildNodeFacetTreeBuilder();
    ftb.initialiseParameters(params);//from www.  j a  v a 2s.c  om

    verify(params).get(FacetTreeParameters.NODE_FIELD_PARAM);
    verify(params).get(QueryParsing.V);
}

From source file:uk.co.flax.biosolr.builders.ChildNodeFacetTreeBuilderTest.java

License:Apache License

@Test(expected = org.apache.solr.search.SyntaxError.class)
public void initialiseParameters_missingChildField() throws Exception {
    final String nodeField = "node";
    final String childField = null;
    final SolrParams params = mock(SolrParams.class);
    when(params.get(FacetTreeParameters.NODE_FIELD_PARAM)).thenReturn(null);
    when(params.get(QueryParsing.V)).thenReturn(nodeField);
    when(params.get(FacetTreeParameters.CHILD_FIELD_PARAM)).thenReturn(childField);

    ChildNodeFacetTreeBuilder ftb = new ChildNodeFacetTreeBuilder();
    ftb.initialiseParameters(params);//  ww  w  .java 2  s.c  o m

    verify(params).get(FacetTreeParameters.NODE_FIELD_PARAM);
    verify(params).get(QueryParsing.V);
    verify(params).get(FacetTreeParameters.CHILD_FIELD_PARAM);
}

From source file:uk.co.flax.biosolr.HierarchicalFacets.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
public SimpleOrderedMap<NamedList> process(String[] facetTrees) throws IOException {
    if (!rb.doFacets || facetTrees == null || facetTrees.length == 0) {
        return null;
    }/* ww w.jav  a 2  s  .  c  o m*/

    int maxThreads = req.getParams().getInt(FacetParams.FACET_THREADS, 0);
    Executor executor = maxThreads == 0 ? directExecutor : facetExecutor;
    final Semaphore semaphore = new Semaphore((maxThreads <= 0) ? Integer.MAX_VALUE : maxThreads);
    List<Future<NamedList>> futures = new ArrayList<>(facetTrees.length);

    SimpleOrderedMap<NamedList> treeResponse = new SimpleOrderedMap<>();
    try {
        FacetTreeBuilderFactory treeBuilderFactory = new FacetTreeBuilderFactory();
        PrunerFactory prunerFactory = new PrunerFactory(parameters);

        for (String fTree : facetTrees) {
            try {
                ParsedParams parsedParams = parseParams(FacetTreeParameters.LOCAL_PARAM_TYPE, fTree);
                SolrParams localParams = parsedParams.localParams;
                FacetTreeBuilder treeBuilder = treeBuilderFactory.constructFacetTreeBuilder(localParams);
                final String localKey = localParams.get(QueryParsing.V);

                final FacetTreeGenerator generator = new FacetTreeGenerator(treeBuilder,
                        localParams.get(FacetTreeParameters.COLLECTION_PARAM, null),
                        prunerFactory.constructPruner(localParams));
                final NamedList<Integer> termCounts = getTermCounts(localKey, parsedParams);
                Callable<NamedList> callable = new Callable<NamedList>() {
                    @Override
                    public NamedList call() throws Exception {
                        try {
                            List<SimpleOrderedMap<Object>> tree = generator.generateTree(rb, termCounts);
                            NamedList<List<SimpleOrderedMap<Object>>> nl = new NamedList<>();
                            nl.add(localKey, tree);
                            return nl;
                        } finally {
                            semaphore.release();
                        }
                    }
                };

                RunnableFuture<NamedList> runnableFuture = new FutureTask<>(callable);
                semaphore.acquire();// may block and/or interrupt
                executor.execute(runnableFuture);// releases semaphore when done
                futures.add(runnableFuture);
            } catch (SyntaxError e) {
                throw new SolrException(ErrorCode.BAD_REQUEST, e);
            }
        }

        // Loop over futures to get the values. The order is the same as
        // facetTrees but shouldn't matter.
        for (Future<NamedList> future : futures) {
            treeResponse.addAll(future.get());
        }
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error while processing facet tree fields: InterruptedException", e);
    } catch (ExecutionException ee) {
        Throwable e = ee.getCause();// unwrap
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error while processing facet tree fields: " + e.toString(), e);
    }

    return treeResponse;
}

From source file:uk.co.flax.biosolr.TreeFacetComponent.java

License:Apache License

private void addTreeFieldsToFacets(ResponseBuilder rb) throws SyntaxError {
    String[] ftFields = rb.req.getParams().getParams(FACET_TREE_FIELD);
    if (ftFields == null || ftFields.length == 0) {
        LOGGER.warn("No facet tree fields specified - ignoring facet trees");
    } else {// ww  w  .  j  av  a2 s.  c o m
        // Take a modifiable copy of the incoming params
        ModifiableSolrParams params = new ModifiableSolrParams(rb.req.getParams());

        // Put the original facet fields (if any) into a Set
        Set<String> facetFields = new LinkedHashSet<>();
        if (params.getParams(FacetParams.FACET_FIELD) != null) {
            facetFields.addAll(Arrays.asList(params.getParams(FacetParams.FACET_FIELD)));
        }

        // Add the facet tree fields
        for (String ftField : ftFields) {
            // Parse the facet tree field, so we only add the field value,
            // rather than the whole string (ensure it's unique)
            facetFields.add(QueryParsing.getLocalParams(ftField, params).get(QueryParsing.V));
        }

        // Add the (possibly) new facet fields
        params.set(FacetParams.FACET_FIELD, facetFields.toArray(new String[facetFields.size()]));

        // Re-set the params in the request
        rb.req.setParams(params);
    }
}