Java Code Examples for org.apache.solr.search.SyntaxError

The following examples show how to use org.apache.solr.search.SyntaxError. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: vind   Source File: FacetMapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws SyntaxError {

    HashMap<String, String> dateIntervals = new HashMap<>();
    dateIntervals.put("after","[NOW+23DAYS/DAY TO *]");
    dateIntervals.put("before","[* TO NOW+23DAYS/DAY]");

    HashMap<String, String> numberIntervals = new HashMap<>();
    numberIntervals.put("bigger","[23 TO *]");
    numberIntervals.put("smaller","[* TO 22]");

    SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> testDateField = new FieldDescriptorBuilder().buildUtilDateField("test1");
    FieldDescriptor<Float> testNumericField = new FieldDescriptorBuilder().buildNumericField("numericTest", Float.class);

    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(testDateField, "dateFacet",dateIntervals).getName().equals("dateFacet"));
    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(testNumericField, "numericFacet", numberIntervals).getName().equals("numericFacet"));

    Assert.assertTrue(true);
}
 
Example 2
Source Project: vind   Source File: FacetMapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexField() throws SyntaxError {

    HashMap<String, String> dateIntervals = new HashMap<>();
    dateIntervals.put("after","[NOW+23DAYS/DAY TO *]");
    dateIntervals.put("before","[* TO NOW+23DAYS/DAY]");

    HashMap<String, String> numberIntervals = new HashMap<>();
    numberIntervals.put("bigger","[23 TO *]");
    numberIntervals.put("smaller","[* TO 22]");

    SingleValuedComplexField.UtilDateComplexField<Taxonomy,Date,Date> complexDateField = new ComplexFieldDescriptorBuilder<Taxonomy,Date,Date>()
            .setFacet(true, tax -> Arrays.asList(tax.getDate()))
            .buildUtilDateComplexField("complexDateTax", Taxonomy.class, Date.class, Date.class);

    SingleValuedComplexField.NumericComplexField<Taxonomy,Number,Number> complexNumberField = new ComplexFieldDescriptorBuilder<Taxonomy,Number,Number>()
            .setFacet(true, tax -> Arrays.asList(tax.getTerm()))
            .buildNumericComplexField("complexNumberTax", Taxonomy.class, Number.class, Number.class);

    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexDateField, "dateFacet",dateIntervals).getName().equals("dateFacet"));
    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexNumberField, "numericFacet", numberIntervals).getName().equals("numericFacet"));

    Assert.assertTrue(true);
}
 
Example 3
public Query parse() throws SyntaxError {
    String reRankQueryString = localParams.get("reRankQuery");
    boolean scale = localParams.getBool("scale", false);
    QParser reRankParser = QParser.getParser(reRankQueryString, null, req);
    Query reRankQuery = reRankParser.parse();

    int reRankDocs  = localParams.getInt("reRankDocs", 200);
    reRankDocs = Math.max(1, reRankDocs); //

    double reRankWeight = localParams.getDouble("reRankWeight",2.0d);

    int start = params.getInt(CommonParams.START,0);
    int rows = params.getInt(CommonParams.ROWS,10);
    int length = start+rows;
    return new ReRankQuery(reRankQuery, reRankDocs, reRankWeight, length, scale);
}
 
Example 4
Source Project: lucene-solr   Source File: NvlValueSourceParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
  ValueSource source = fp.parseValueSource();
  final float nvl = fp.parseFloat();

  return new SimpleFloatFunction(source) {
    @Override
  protected String name() {
      return "nvl";
    }

    @Override
    protected float func(int doc, FunctionValues vals) throws IOException {
      float v = vals.floatVal(doc);
      if (v == nvlFloatValue) {
        return nvl;
      } else {
        return v;
      }
    }
  };
}
 
Example 5
Source Project: lucene-solr   Source File: SimpleFacets.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of facet counts for each of the facet queries
 * specified in the params
 *
 * @see FacetParams#FACET_QUERY
 */
public NamedList<Integer> getFacetQueryCounts() throws IOException,SyntaxError {

  NamedList<Integer> res = new SimpleOrderedMap<>();

  /* Ignore CommonParams.DF - could have init param facet.query assuming
   * the schema default with query param DF intented to only affect Q.
   * If user doesn't want schema default for facet.query, they should be
   * explicit.
   */
  // SolrQueryParser qp = searcher.getSchema().getSolrQueryParser(null);

  String[] facetQs = global.getParams(FacetParams.FACET_QUERY);

  if (null != facetQs && 0 != facetQs.length) {
    for (String q : facetQs) {
      final ParsedParams parsed = parseParams(FacetParams.FACET_QUERY, q);
      getFacetQueryCount(parsed, res);
    }
  }

  return res;
}
 
Example 6
Source Project: lucene-solr   Source File: IntervalFacets.java    License: Apache License 2.0 6 votes vote down vote up
private int unescape(String s, int i, int n, StringBuilder sb) throws SyntaxError {
  for (; i < n; ++i) {
    char c = s.charAt(i);
    if (c == '\\') {
      ++i;
      if (i < n) {
        c = s.charAt(i);
      } else {
        throw new SyntaxError("Unfinished escape at index " + i + " in facet interval " + s);
      }
    } else if (c == ',') {
      return i + 1;
    }
    sb.append(c);
  }
  return n;
}
 
Example 7
@Override
public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
  String trainingFilterQueryString = (params.get(KNN_FILTER_QUERY));
  try {
    if (trainingFilterQueryString != null && !trainingFilterQueryString.isEmpty()) {
      Query trainingFilterQuery = this.parseFilterQuery(trainingFilterQueryString, params, req);
      classificationParams.setTrainingFilterQuery(trainingFilterQuery);
    }
  } catch (SyntaxError | RuntimeException syntaxError) {
    throw new SolrException
        (SolrException.ErrorCode.SERVER_ERROR,
            "Classification UpdateProcessor Training Filter Query: '" + trainingFilterQueryString + "' is not supported", syntaxError);
  }

  IndexSchema schema = req.getSchema();
  IndexReader indexReader = req.getSearcher().getIndexReader();

  return new ClassificationUpdateProcessor(classificationParams, next, indexReader, schema);
}
 
Example 8
Source Project: lucene-solr   Source File: SolrPluginUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes a basic query
 */
public static DocList doSimpleQuery(String sreq,
                                    SolrQueryRequest req,
                                    int start, int limit) throws IOException {
  List<String> commands = StrUtils.splitSmart(sreq,';');

  String qs = commands.size() >= 1 ? commands.get(0) : "";
  try {
  Query query = QParser.getParser(qs, req).getQuery();

  // If the first non-query, non-filter command is a simple sort on an indexed field, then
  // we can use the Lucene sort ability.
  Sort sort = null;
  if (commands.size() >= 2) {
    sort = SortSpecParsing.parseSortSpec(commands.get(1), req).getSort();
  }

  DocList results = req.getSearcher().getDocList(query,(DocSet)null, sort, start, limit);
  return results;
  } catch (SyntaxError e) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing query: " + qs);
  }

}
 
Example 9
Source Project: lucene-solr   Source File: DirectUpdateHandler2.java    License: Apache License 2.0 6 votes vote down vote up
private Query getQuery(DeleteUpdateCommand cmd) {
  Query q;
  try {
    // move this higher in the stack?
    QParser parser = QParser.getParser(cmd.getQuery(), cmd.req);
    q = parser.getQuery();
    q = QueryUtils.makeQueryable(q);

    // Make sure not to delete newer versions
    if (ulog != null && cmd.getVersion() != 0 && cmd.getVersion() != -Long.MAX_VALUE) {
      BooleanQuery.Builder bq = new BooleanQuery.Builder();
      bq.add(q, Occur.MUST);
      SchemaField sf = ulog.getVersionInfo().getVersionField();
      ValueSource vs = sf.getType().getValueSource(sf, null);
      ValueSourceRangeFilter filt = new ValueSourceRangeFilter(vs, Long.toString(Math.abs(cmd.getVersion())), null, true, true);
      FunctionRangeQuery range = new FunctionRangeQuery(filt);
      bq.add(range, Occur.MUST_NOT);  // formulated in the "MUST_NOT" sense so we can delete docs w/o a version (some tests depend on this...)
      q = bq.build();
    }

    return q;

  } catch (SyntaxError e) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
  }
}
 
Example 10
Source Project: lucene-solr   Source File: GeoDistValueSourceParser.java    License: Apache License 2.0 6 votes vote down vote up
private MultiValueSource parseSfield(FunctionQParser fp) throws SyntaxError {
  String sfield = fp.getParam(SpatialParams.FIELD);
  if (sfield == null) return null;
  SchemaField sf = fp.getReq().getSchema().getField(sfield);
  FieldType type = sf.getType();
  if (type instanceof AbstractSpatialFieldType) {
    @SuppressWarnings({"rawtypes"})
    AbstractSpatialFieldType asft = (AbstractSpatialFieldType) type;
    return new SpatialStrategyMultiValueSource(asft.getStrategy(sfield), asft.getDistanceUnits());
  }
  ValueSource vs = type.getValueSource(sf, fp);
  if (vs instanceof MultiValueSource) {
    return (MultiValueSource)vs;
  }
  throw new SyntaxError("Spatial field must implement MultiValueSource or extend AbstractSpatialFieldType:" + sf);
}
 
Example 11
Source Project: lucene-solr   Source File: FacetParser.java    License: Apache License 2.0 6 votes vote down vote up
/** Parses simple strings like "avg(x)" or robust Maps that may contain local params */
private AggValueSource parseStat(String key, Object args) throws SyntaxError {
  assert null != args;

  if (args instanceof CharSequence) {
    // Both of these variants are already unpacked for us in this case, and use no local params...
    // 1) x:{func:'min(foo)'}
    // 2) x:'min(foo)'
    return parseStatWithParams(key, null, args.toString());
  }

  if (args instanceof Map) {
    @SuppressWarnings({"unchecked"})
    final Map<String,Object> statMap = (Map<String,Object>)args;
    return parseStatWithParams(key, jsonToSolrParams(statMap), statMap.get("func").toString());
  }

  throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
      "Stats must be specified as either a simple string, or a json Map");

}
 
Example 12
Source Project: lucene-solr   Source File: PercentileAgg.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
  List<Double> percentiles = new ArrayList<>();
  ValueSource vs = fp.parseValueSource();
  while (fp.hasMoreArguments()) {
    double val = fp.parseDouble();
    if (val<0 || val>100) {
      throw new SyntaxError("requested percentile must be between 0 and 100.  got " + val);
    }
    percentiles.add(val);
  }

  if (percentiles.isEmpty()) {
    throw new SyntaxError("expected percentile(valsource,percent1[,percent2]*)  EXAMPLE:percentile(myfield,50)");
  }

  return new PercentileAgg(vs, percentiles);
}
 
Example 13
Source Project: lucene-solr   Source File: GraphQueryParser.java    License: Apache License 2.0 6 votes vote down vote up
public void validateFields(String field) throws SyntaxError {

    if (req.getSchema().getField(field) == null) {
      throw new SyntaxError("field " + field + " not defined in schema");
    }

    if (req.getSchema().getField(field).getType().isPointField()) {
      if (req.getSchema().getField(field).hasDocValues()) {
        return;
      } else {
        throw new SyntaxError("point field " + field + " must have docValues=true");
      }
    }

    if (req.getSchema().getField(field).getType() instanceof StrField) {
      if ((req.getSchema().getField(field).hasDocValues() || req.getSchema().getField(field).indexed())) {
        return;
      } else {
        throw new SyntaxError("string field " + field + " must have indexed=true or docValues=true");
      }
    }

    throw new SyntaxError("FieldType for field=" + field + " not supported");

  }
 
Example 14
Source Project: ltr4l   Source File: DefaultLTRQParserPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Query parse() throws SyntaxError {
  IndexReaderContext context = req.getSearcher().getTopReaderContext();
  for(FieldFeatureExtractorFactory factory: featuresSpec){
    String fieldName = factory.getFieldName();
    FieldType fieldType = req.getSchema().getFieldType(fieldName);
    Analyzer analyzer = fieldType.getQueryAnalyzer();
    factory.init(context, FieldFeatureExtractorFactory.terms(fieldName, qstr, analyzer));
  }

  return new DefaultLTRQuery(featuresSpec, ranker);
}
 
Example 15
Source Project: lucene-solr   Source File: RangeFacetProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes"})
private <T extends Comparable<T>> NamedList getFacetRangeCounts(final RangeFacetRequest rfr)
    throws IOException, SyntaxError {

  final NamedList<Object> res = new SimpleOrderedMap<>();
  final NamedList<Integer> counts = new NamedList<>();
  res.add("counts", counts);

  // explicitly return the gap.
  res.add("gap", rfr.getGapObj());

  DocSet docSet = computeDocSet(docsOrig, rfr.getExcludeTags());

  for (RangeFacetRequest.FacetRange range : rfr.getFacetRanges()) {
    if (range.other != null) {
      // these are added to top-level NamedList
      // and we always include them regardless of mincount
      res.add(range.other.toString(), rangeCount(docSet, rfr, range));
    } else {
      final int count = rangeCount(docSet, rfr, range);
      if (count >= rfr.getMinCount()) {
        counts.add(range.lower, count);
      }
    }
  }

  // explicitly return the start and end so all the counts
  // (including before/after/between) are meaningful - even if mincount
  // has removed the neighboring ranges
  res.add("start", rfr.getStartObj());
  res.add("end", rfr.getEndObj());

  return res;
}
 
Example 16
Source Project: solr-vector-scoring   Source File: VectorQParserPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
	return new QParser(qstr, localParams, params, req) {
		@Override
		public Query parse() throws SyntaxError {
			String field = localParams.get(QueryParsing.F);
			String vector = localParams.get("vector");
			boolean cosine = localParams.getBool("cosine", true);

			if (field == null) {
				throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'f' not specified");
			}

			if (vector == null) {
				throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "vector missing");
			}

			Query subQuery = subQuery(localParams.get(QueryParsing.V), null).getQuery();

			FieldType ft = req.getCore().getLatestSchema().getFieldType(field);
			if(ft != null) {
				VectorQuery q = new VectorQuery(subQuery);
				q.setQueryString(localParams.toLocalParamsString()); 
				query = q;
			}
		

			if (query == null) {
				throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Query is null");
			}

			return new VectorScoreQuery(query, vector, field, cosine);

		}
	};
}
 
Example 17
Source Project: solr-custom-score   Source File: MyParser.java    License: Apache License 2.0 5 votes vote down vote up
public MyParser(List<String> pfield,String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    super(qstr, localParams, params, req);
    try {
        QParser parser = getParser(qstr, "lucene", getReq());
        this.innerQuery = parser.parse();
    } catch (SyntaxError ex) {
        throw new RuntimeException("error parsing query", ex);
    }
    this.params=pfield;
}
 
Example 18
Source Project: lucene-solr   Source File: TestIntervalFaceting.java    License: Apache License 2.0 5 votes vote down vote up
private void assertIntervalKey(String fieldName, String intervalStr,
    String expectedKey, String...params) throws SyntaxError {
  assert (params.length&1)==0:"Params must have an even number of elements";
  SchemaField f = h.getCore().getLatestSchema().getField(fieldName);
  ModifiableSolrParams solrParams = new ModifiableSolrParams();
  for (int i = 0; i < params.length - 1;) {
    solrParams.set(params[i], params[i+1]);
    i+=2;
  }
  FacetInterval interval = new FacetInterval(f, intervalStr, solrParams);
  
  assertEquals("Expected key " + expectedKey + " but found " + interval.getKey(), 
      expectedKey, interval.getKey());
}
 
Example 19
Source Project: lucene-solr   Source File: SolrQueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
/** Parses a query string, returning a {@link org.apache.lucene.search.Query}.
  *  @param query  the query string to be parsed.
  */
public Query parse(String query) throws SyntaxError {
  ReInit(new FastCharStream(new StringReader(query)));
  try {
    // TopLevelQuery is a Query followed by the end-of-input (EOF)
    Query res = TopLevelQuery(null);  // pass null so we can tell later if an explicit field was provided or not
    return res!=null ? res : newBooleanQuery().build();
  }
  catch (ParseException | TokenMgrError tme) {
    throw new SyntaxError("Cannot parse '" +query+ "': " + tme.getMessage(), tme);
  } catch (IndexSearcher.TooManyClauses tmc) {
    throw new SyntaxError("Cannot parse '" +query+ "': too many boolean clauses", tmc);
  }
}
 
Example 20
Source Project: lucene-solr   Source File: ScoreModeParser.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * recognizes as-is {@link ScoreMode} names, and lowercase as well, 
 * otherwise throws exception 
 * @throws SyntaxError when it's unable to parse
 * */
static ScoreMode parse(String score) throws SyntaxError {
  final ScoreMode scoreMode = lowerAndCapitalCase.get(score);
  if (scoreMode == null) {
    throw new SyntaxError("Unable to parse ScoreMode from: " + score);
  }
  return scoreMode;
}
 
Example 21
Source Project: lucene-solr   Source File: SolrQueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Base implementation delegates to {@link #getFieldQuery(String,String,boolean,boolean)}.
 * This method may be overridden, for example, to return
 * a SpanNearQuery instead of a PhraseQuery.
 *
 */
protected Query getFieldQuery(String field, String queryText, int slop)
      throws SyntaxError {
  Query query = getFieldQuery(field, queryText, true, false);

  // only set slop of the phrase query was a result of this parser
  // and not a sub-parser.
  if (subQParser == null) {
    if (query instanceof PhraseQuery) {
      PhraseQuery pq = (PhraseQuery) query;
      Term[] terms = pq.getTerms();
      int[] positions = pq.getPositions();
      PhraseQuery.Builder builder = new PhraseQuery.Builder();
      for (int i = 0; i < terms.length; ++i) {
        builder.add(terms[i], positions[i]);
      }
      builder.setSlop(slop);
      query = builder.build();
    } else if (query instanceof MultiPhraseQuery) {
      MultiPhraseQuery mpq = (MultiPhraseQuery)query;

      if (slop != mpq.getSlop()) {
        query = new MultiPhraseQuery.Builder(mpq).setSlop(slop).build();
      }
    }
  }

  return query;
}
 
Example 22
Source Project: lucene-solr   Source File: SolrQueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
Query handleQuotedTerm(String qfield, Token term, Token fuzzySlop) throws SyntaxError {
  int s = phraseSlop;  // default
  if (fuzzySlop != null) {
    try {
      s = (int)Float.parseFloat(fuzzySlop.image.substring(1));
    }
    catch (Exception ignored) { }
  }

  String raw = discardEscapeChar(term.image.substring(1, term.image.length()-1));
  return getFieldQuery(qfield, raw, s);
}
 
Example 23
Source Project: lucene-solr   Source File: SolrPluginUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Turns an array of query strings into a List of Query objects.
 *
 * @return null if no queries are generated
 */
public static List<Query> parseQueryStrings(SolrQueryRequest req,
                                            String[] queries) throws SyntaxError {
  if (null == queries || 0 == queries.length) return null;
  List<Query> out = new ArrayList<>(queries.length);
  for (String q : queries) {
    if (null != q && 0 != q.trim().length()) {
      out.add(QParser.getParser(q, req).getQuery());
    }
  }
  return out;
}
 
Example 24
Source Project: lucene-solr   Source File: TestScoreJoinQPNoScore.java    License: Apache License 2.0 5 votes vote down vote up
public void testNotEquals() throws SyntaxError, IOException{
  try (SolrQueryRequest req = req("*:*")) {
    Query x = QParser.getParser("{!join from=dept_id_s to=dept_ss score=none}text_t:develop", req).getQuery();
    Query y = QParser.getParser("{!join from=dept_ss to=dept_ss score=none}text_t:develop", req).getQuery();
    assertFalse("diff from fields produce equal queries",
                x.equals(y));
  }
}
 
Example 25
Source Project: lucene-solr   Source File: HashRangeQParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Query parse() throws SyntaxError {
  String field = localParams.get(FIELD);
  int lower = localParams.getInt(LOWER_BOUND);
  int upper = localParams.getInt(UPPER_BOUND);

  return new HashRangeQuery(field, lower, upper);
}
 
Example 26
Source Project: lucene-solr   Source File: SolrQueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
protected Query getLocalParams(String qfield, String lparams) throws SyntaxError {
  if (!allowSubQueryParsing) {
    throw new SyntaxError("local-params subquery is disabled");
  }
  QParser nested = parser.subQuery(lparams, null);
  return nested.getQuery();
}
 
Example 27
Source Project: lucene-solr   Source File: QueryParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Query newFieldQuery(Analyzer analyzer, String field, String queryText,
                              boolean quoted, boolean fieldAutoGenPhraseQueries,
                              boolean fieldEnableGraphQueries,
                               SynonymQueryStyle synonymQueryStyle)
    throws SyntaxError {
  setAutoGenerateMultiTermSynonymsPhraseQuery(fieldAutoGenPhraseQueries || getAutoGeneratePhraseQueries());
  // Don't auto-quote graph-aware field queries 
  boolean treatAsQuoted = getSplitOnWhitespace()
      ? (quoted || fieldAutoGenPhraseQueries || getAutoGeneratePhraseQueries()) : quoted;
  return super.newFieldQuery(analyzer, field, queryText, treatAsQuoted, false,
  fieldEnableGraphQueries, synonymQueryStyle);
}
 
Example 28
Source Project: lucene-solr   Source File: QueryParser.java    License: Apache License 2.0 5 votes vote down vote up
final public Query TopLevelQuery(String field) throws ParseException, SyntaxError {
Query q;
  q = Query(field);
  jj_consume_token(0);
  {if (true) return q;}
  throw new Error("Missing return statement in function");
}
 
Example 29
Source Project: query-segmenter   Source File: QuerySegmenterQParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Query parse() throws SyntaxError {

  String qstr = getString();

  List<TypedSegment> typedSegments = segmenter.segment(qstr);
  List<Query> boostQueries = new ArrayList<>();

  for (TypedSegment typedSegment : typedSegments) {
    FieldMapping mapping = mappings.get(typedSegment.getDictionaryName());
    String value = QuerySegmenterComponent.getValue(typedSegment, mapping);
    if (mapping.useBoostQuery) {
      qstr = qstr.replaceFirst(typedSegment.getSegment(), "");
      String qs = String.format("%s:%s", mapping.field, value);
      boostQueries.add(subQuery(qs, null).getQuery());
    } else {
      qstr = qstr.replaceFirst(typedSegment.getSegment(), String.format("%s:%s", mapping.field, value));
    }
  }

  // Passing null allows to use another qparser defined with defType (like edismax)
  // See SOLR-2972
  QParser parser = subQuery(qstr, null);
  BooleanQuery.Builder query = new BooleanQuery.Builder();
  query.add(parser.parse(), BooleanClause.Occur.MUST);

  for(Query bq:boostQueries) {
    query.add(bq, BooleanClause.Occur.SHOULD);
  }
  return query.build();
}
 
Example 30
Source Project: lucene-solr   Source File: SimpleFacets.java    License: Apache License 2.0 5 votes vote down vote up
public void getFacetQueryCount(ParsedParams parsed, NamedList<Integer> res) throws SyntaxError, IOException {
  // TODO: slight optimization would prevent double-parsing of any localParams
  // TODO: SOLR-7753
  Query qobj = QParser.getParser(parsed.facetValue, req).getQuery();

  if (qobj == null) {
    res.add(parsed.key, 0);
  } else if (parsed.params.getBool(GroupParams.GROUP_FACET, false)) {
    res.add(parsed.key, getGroupedFacetQueryCount(qobj, parsed.docs));
  } else {
    res.add(parsed.key, searcher.numDocs(qobj, parsed.docs));
  }
}