Java Code Examples for org.apache.solr.schema.IndexSchema#getField()

The following examples show how to use org.apache.solr.schema.IndexSchema#getField() . 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 File: MtasSolrComponentFacet.java    From mtas with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the field type.
 *
 * @param schema the schema
 * @param field the field
 * @return the field type
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String getFieldType(IndexSchema schema, String field)
    throws IOException {
  SchemaField sf = schema.getField(field);
  FieldType ft = sf.getType();
  if (ft != null) {
    if (ft.isPointField() && !sf.hasDocValues()) {
      return ComponentFacet.TYPE_POINTFIELD_WITHOUT_DOCVALUES;
    }
    NumberType nt = ft.getNumberType();
    if (nt != null) {
      return nt.name();
    } else {
      return ComponentFacet.TYPE_STRING;
    }
  } else {
    // best guess
    return ComponentFacet.TYPE_STRING;
  }
}
 
Example 2
Source File: QueryAutoFilteringComponent.java    From query-autofiltering-component with Apache License 2.0 6 votes vote down vote up
private ArrayList<String> getStringFields( SolrIndexSearcher searcher ) {
  IndexSchema schema = searcher.getSchema();
  ArrayList<String> strFields = new ArrayList<String>( );
    
  Collection<String> fieldNames = searcher.getFieldNames();
  Iterator<String> fnIt = fieldNames.iterator();
  while ( fnIt.hasNext() ) {
    String fieldName = fnIt.next( );
    if (excludeFields == null || !excludeFields.contains( fieldName )) {
      try {
        SchemaField field = schema.getField(fieldName);
        if (field.stored() && field.getType() instanceof StrField ) {
          strFields.add( fieldName );
        }
      }
      catch (Throwable e )
      {
          
      }
    }
  }
    
  return strFields;
}
 
Example 3
Source File: SolrMorphlineTest.java    From kite with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadManagedSchema() throws Exception {
  // Copy the collection1 config files, so we don't have to keep multiple
  // copies of the auxiliary files in source
  File solrHomeDir = Files.createTempDir();
  solrHomeDir.deleteOnExit();
  File collection1Dir = new File(SOLR_INSTANCE_DIR, "collection1");
  FileUtils.copyDirectory(collection1Dir, solrHomeDir);

  // Copy in the managed collection files, remove the schema.xml since the
  // managed schema uses a generated one
  File managedCollectionDir = new File(SOLR_INSTANCE_DIR, "managedSchemaCollection");
  FileUtils.copyDirectory(managedCollectionDir, solrHomeDir);
  File oldSchemaXml = new File(solrHomeDir + File.separator + "conf" + File.separator + "schema.xml");
  oldSchemaXml.delete();
  assertFalse(oldSchemaXml.exists());

  SolrLocator locator = new SolrLocator(new MorphlineContext.Builder().build());
  locator.setCollectionName("managedSchemaCollection");
  locator.setSolrHomeDir(solrHomeDir.getAbsolutePath());
  IndexSchema schema = locator.getIndexSchema();
  assertNotNull(schema);
  schema.getField("test-managed-morphline-field");
}
 
Example 4
Source File: TopGroupsResultTransformer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public NamedList transform(List<Command> data) throws IOException {
  NamedList<NamedList> result = new NamedList<>();
  final IndexSchema schema = rb.req.getSearcher().getSchema();
  for (Command command : data) {
    NamedList commandResult;
    if (TopGroupsFieldCommand.class.isInstance(command)) {
      TopGroupsFieldCommand fieldCommand = (TopGroupsFieldCommand) command;
      SchemaField groupField = schema.getField(fieldCommand.getKey());
      commandResult = serializeTopGroups(fieldCommand.result(), groupField);
    } else if (QueryCommand.class.isInstance(command)) {
      QueryCommand queryCommand = (QueryCommand) command;
      commandResult = serializeTopDocs(queryCommand.result());
    } else {
      commandResult = null;
    }

    result.add(command.getKey(), commandResult);
  }
  return result;
}
 
Example 5
Source File: TestSolr4Spatial.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpatialConfig() throws Exception {
  try (SolrCore core = h.getCoreInc())  {
    IndexSchema schema = core.getLatestSchema();

    // BBox Config
    // Make sure the subfields are not stored
    SchemaField sub = schema.getField("bbox"+BBoxStrategy.SUFFIX_MINX);
    assertFalse(sub.stored());

    // Make sure solr field type is also not stored
    BBoxField bbox = (BBoxField)schema.getField("bbox").getType();
    BBoxStrategy strategy = bbox.getStrategy("bbox");
    assertFalse(strategy.getFieldType().stored());
  }
}
 
Example 6
Source File: QueryAutoFilteringComponent.java    From query-autofiltering-component with Apache License 2.0 6 votes vote down vote up
private ArrayList<String> getStringFields( SolrIndexSearcher searcher ) {
  IndexSchema schema = searcher.getSchema();
  ArrayList<String> strFields = new ArrayList<String>( );
    
  Collection<String> fieldNames = searcher.getFieldNames();
  Iterator<String> fnIt = fieldNames.iterator();
  while ( fnIt.hasNext() ) {
    String fieldName = fnIt.next( );
    if (excludeFields == null || !excludeFields.contains( fieldName )) {
      SchemaField field = schema.getField(fieldName);
      if (field.stored() && field.getType() instanceof StrField ) {
        strFields.add( fieldName );
      }
    }
  }
    
  return strFields;
}
 
Example 7
Source File: TestDocBasedVersionConstraints.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testCanCreateTombstonesMissingRequiredField() {
  DocBasedVersionConstraintsProcessorFactory factory = new DocBasedVersionConstraintsProcessorFactory();
  NamedList<Object> config = new NamedList<>();
  config.add("versionField", "_version_");
  factory.init(config);
  IndexSchema schema = h.getCore().getLatestSchema();
  SchemaField sf = schema.getField("sku1");
  assertThat(sf, is(not(nullValue())));
  assertThat(schema.getRequiredFields(), not(hasItem(sf)));
  try {
    schema.getRequiredFields().add(sf);
    assertThat(factory.canCreateTombstoneDocument(schema), is(false));
  } finally {
    schema.getRequiredFields().remove(sf);
  }
}
 
Example 8
Source File: TestDocBasedVersionConstraints.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testCanCreateTombstonesVersionFieldRequired() {
  DocBasedVersionConstraintsProcessorFactory factory = new DocBasedVersionConstraintsProcessorFactory();
  NamedList<Object> config = new NamedList<>();
  config.add("versionField", "_version_");
  factory.init(config);
  IndexSchema schema = h.getCore().getLatestSchema();
  SchemaField versionField = schema.getField("_version_");
  assertThat(versionField, is(not(nullValue())));
  assertThat(schema.getRequiredFields(), not(hasItem(versionField)));
  try {
    schema.getRequiredFields().add(versionField);
    assertThat(factory.canCreateTombstoneDocument(schema), is(true));
  } finally {
    schema.getRequiredFields().remove(versionField);
  }
}
 
Example 9
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> toObject(IndexSchema schema) {
  Map<String,Object> result = new HashMap<>();
  for (Fld fld : fields) {
    SchemaField sf = schema.getField(fld.ftype.fname);
    if (!sf.multiValued()) {
      result.put(fld.ftype.fname, fld.vals.get(0));
    } else {
      result.put(fld.ftype.fname, fld.vals);
    }
  }
  return result;
}
 
Example 10
Source File: UninvertDocValuesMergePolicyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static void implUpdateSchemaField(TestHarness h, String fieldName, IntUnaryOperator propertiesModifier) {
  try (SolrCore core = h.getCoreInc()) {

    // Add docvalues to the field type
    IndexSchema schema = core.getLatestSchema();
    SchemaField oldSchemaField = schema.getField(fieldName);
    SchemaField newSchemaField = new SchemaField(
        fieldName,
        oldSchemaField.getType(),
        propertiesModifier.applyAsInt(oldSchemaField.getProperties()),
        oldSchemaField.getDefaultValue());
    schema.getFields().put(fieldName, newSchemaField);
  }
}
 
Example 11
Source File: TestDocBasedVersionConstraints.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testCanCreateTombstonesUniqueKeyFieldRequired() {
  DocBasedVersionConstraintsProcessorFactory factory = new DocBasedVersionConstraintsProcessorFactory();
  NamedList<Object> config = new NamedList<>();
  config.add("versionField", "_version_");
  factory.init(config);
  IndexSchema schema = h.getCore().getLatestSchema();
  SchemaField uniqueKeyField = schema.getField("id");
  assertThat(uniqueKeyField, is(not(nullValue())));
  assertThat(uniqueKeyField, equalTo(schema.getUniqueKeyField()));
  assertThat(schema.getRequiredFields(), hasItem(schema.getUniqueKeyField()));
  assertThat(factory.canCreateTombstoneDocument(schema), is(true));
}
 
Example 12
Source File: AbstractFacetTreeBuilder.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
protected void checkFieldsInSchema(SolrIndexSearcher searcher, Collection<String> fields) throws SolrException {
	IndexSchema schema = searcher.getSchema();
	for (String field : fields) {
		SchemaField sField = schema.getField(field);
		if (sField == null) {
			throw new SolrException(ErrorCode.BAD_REQUEST, "\"" + field
					+ "\" is not in schema " + schema.getSchemaName());
		}
	}
}
 
Example 13
Source File: DocBasedVersionConstraintsProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public DocBasedVersionConstraintsProcessor(List<String> versionFields,
                                           boolean ignoreOldUpdates,
                                           List<String> deleteVersionParamNames,
                                           boolean supportMissingVersionOnOldDocs,
                                           boolean useFieldCache,
                                           NamedList<Object> tombstoneConfig,
                                           SolrQueryRequest req,
                                           UpdateRequestProcessor next ) {
  super(next);
  this.ignoreOldUpdates = ignoreOldUpdates;
  this.deleteVersionParamNames = deleteVersionParamNames.toArray(EMPTY_STR_ARR);
  this.supportMissingVersionOnOldDocs = supportMissingVersionOnOldDocs;
  this.core = req.getCore();
  this.versionFieldNames = versionFields.toArray(EMPTY_STR_ARR);
  IndexSchema schema = core.getLatestSchema();
  userVersionFields = new SchemaField[versionFieldNames.length];
  for (int i = 0; i < versionFieldNames.length; i++) {
    userVersionFields[i] = schema.getField(versionFieldNames[i]);
  }
  this.solrVersionField = schema.getField(CommonParams.VERSION_FIELD);
  this.useFieldCache = useFieldCache;

  this.distribProc = getDistributedUpdateProcessor(next);

  this.phase = DistributedUpdateProcessor.DistribPhase.parseParam(req.getParams().get(DISTRIB_UPDATE_PARAM));
  this.tombstoneConfig = tombstoneConfig;
}
 
Example 14
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Comparator<Doc> createSort(IndexSchema schema, List<FldType> fieldTypes, String[] out) {
  StringBuilder sortSpec = new StringBuilder();
  int nSorts = random().nextInt(4);
  List<Comparator<Doc>> comparators = new ArrayList<>();
  for (int i=0; i<nSorts; i++) {
    if (i>0) sortSpec.append(',');

    int which = random().nextInt(fieldTypes.size()+2);
    boolean asc = random().nextBoolean();
    if (which == fieldTypes.size()) {
      // sort by score
      sortSpec.append("score").append(asc ? " asc" : " desc");
      comparators.add(createComparator("score", asc, false, false, false));
    } else if (which == fieldTypes.size() + 1) {
      // sort by docid
      sortSpec.append("_docid_").append(asc ? " asc" : " desc");
      comparators.add(createComparator("_docid_", asc, false, false, false));
    } else {
      String field = fieldTypes.get(which).fname;
      sortSpec.append(field).append(asc ? " asc" : " desc");
      SchemaField sf = schema.getField(field);
      comparators.add(createComparator(field, asc, sf.sortMissingLast(), sf.sortMissingFirst(), !(sf.sortMissingLast()||sf.sortMissingFirst()) ));
    }
  }

  out[0] = sortSpec.length() > 0 ? sortSpec.toString() : null;

  if (comparators.size() == 0) {
    // default sort is by score desc
    comparators.add(createComparator("score", false, false, false, false));      
  }

  return createComparator(comparators);
}
 
Example 15
Source File: SolrTestCaseHS.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Map<String,Object> toObject(Doc doc, IndexSchema schema, Collection<String> fieldNames) {
  Map<String,Object> result = new HashMap<>();
  for (Fld fld : doc.fields) {
    if (fieldNames != null && !fieldNames.contains(fld.ftype.fname)) continue;
    SchemaField sf = schema.getField(fld.ftype.fname);
    if (!sf.multiValued()) {
      result.put(fld.ftype.fname, fld.vals.get(0));
    } else {
      result.put(fld.ftype.fname, fld.vals);
    }
  }
  return result;
}
 
Example 16
Source File: QueryAutoFilteringComponent.java    From query-autofiltering-component with Apache License 2.0 4 votes vote down vote up
private String getFilterQuery( ResponseBuilder rb, String fieldName, ArrayList<String> valList,
                               int[] termPosRange, ArrayList<char[]> queryTokens, String suffix) {
  if (fieldName.indexOf( fieldDelim ) > 0) {
    return getFilterQuery( rb, fieldName.split( fieldSplitExpr ), valList, termPosRange, queryTokens, suffix );
  }
  if (valList.size() == 1) {
    // check if valList[0] is multi-term - if so, check if there is a single term equivalent
    // if this returns non-null, create an OR query with single term version
    // example "white linen perfume" vs "white linen shirt"  where "White Linen" is a brand
    String term = valList.get( 0 );
      
    if (term.indexOf( " " ) > 0) {
      String singleTermQuery = getSingleTermQuery( term );
      if (singleTermQuery != null) {
        StringBuilder strb = new StringBuilder( );
        // EH: possible meta-escaping problem if value includes {!field f=<fieldName>}value
        strb.append( "(" ).append( fieldName ).append( ":" )
            .append( term ).append( " OR (" ).append( singleTermQuery ).append( "))" ).append( suffix );
        Log.debug( "returning composite query: " + strb.toString( ) );
        return strb.toString( );
      }
    }
      
    String query = fieldName + ":" + term + suffix;
    Log.debug( "returning single query: " + query );
    return query;
  }
  else {
    SolrIndexSearcher searcher = rb.req.getSearcher();
    IndexSchema schema = searcher.getSchema();
    SchemaField field = schema.getField(fieldName);
    boolean useAnd = field.multiValued() && useAndForMultiValuedFields;
    // if query has 'or' in it and or is at a position 'within' the values for this field ...
    if (useAnd) {
      for (int i = termPosRange[0] + 1; i < termPosRange[1]; i++ ) {
        char[] qToken = queryTokens.get( i );
        // is the token 'or'?
        if (qToken.length == 2 && qToken[0] == 'o' && qToken[1] == 'r' ) {
          useAnd = false;
          break;
        }
      }
    }
      
    StringBuilder orQ = new StringBuilder( );
    for (String val : valList ) {
      if (orQ.length() > 0) orQ.append( (useAnd ? " AND " : " OR ") );
      orQ.append( val );
    }
    return fieldName + ":(" + orQ.toString() + ")" + suffix;
  }
}
 
Example 17
Source File: QueryAutoFilteringComponent.java    From query-autofiltering-component with Apache License 2.0 4 votes vote down vote up
private String getFilterQuery( ResponseBuilder rb, String fieldName, ArrayList<String> valList,
                               int[] termPosRange, ArrayList<char[]> queryTokens, String suffix) {
    
  if (fieldName.indexOf( fieldDelim ) > 0) {
    return getFilterQuery( rb, fieldName.split( fieldSplitExpr ), valList, termPosRange, queryTokens, suffix );
  }
  if (valList.size() == 1) {
    // check if valList[0] is multi-term - if so, check if there is a single term equivalent
    // if this returns non-null, create an OR query with single term version
    // example "white linen perfume" vs "white linen shirt"  where "White Linen" is a brand
    String term = valList.get( 0 );

    if (term.indexOf( " " ) > 0) {
      String singleTermQuery = getSingleTermQuery( term );
      if (singleTermQuery != null) {
        StringBuilder strb = new StringBuilder( );
        strb.append( "(" ).append( fieldName ).append( ":" )
            .append( term ).append( " OR (" ).append( singleTermQuery ).append( "))" ).append( suffix );
        Log.debug( "returning composite query: " + strb.toString( ) );
        return strb.toString( );
      }
    }

    String query = fieldName + ":" + term + suffix;
    Log.debug( "returning single query: " + query );
    return query;
  }
  else {
    // Check if it is a MultiValued Field - if so, use AND internally
    SolrIndexSearcher searcher = rb.req.getSearcher();
    IndexSchema schema = searcher.getSchema();
    SchemaField field = schema.getField(fieldName);
      
    boolean useAnd = field.multiValued() && useAndForMultiValuedFields;
    // if query has 'or' in it and or is at a position 'within' the values for this field ...
    if (useAnd) {
      for (int i = termPosRange[0] + 1; i < termPosRange[1]; i++ ) {
        char[] qToken = queryTokens.get( i );
        if (qToken.length == 2 && qToken[0] == 'o' && qToken[1] == 'r' ) {
          useAnd = false;
          break;
        }
      }
    }
      
    StringBuilder orQ = new StringBuilder( );
    for (String val : valList ) {
      if (orQ.length() > 0) orQ.append( (useAnd ? " AND " : " OR ") );
      orQ.append( val );
    }
      
    String fq = fieldName + ":(" + orQ.toString() + ")" + suffix;
    Log.debug( "fq = " + fq );
    return fq;
  }
}
 
Example 18
Source File: ExportWriter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected FieldWriter[] getFieldWriters(String[] fields, SolrIndexSearcher searcher) throws IOException {
  IndexSchema schema = searcher.getSchema();
  FieldWriter[] writers = new FieldWriter[fields.length];
  for (int i = 0; i < fields.length; i++) {
    String field = fields[i];
    SchemaField schemaField = null;

    try {
      schemaField = schema.getField(field);
    } catch (Exception e) {
      throw new IOException(e);
    }

    if (!schemaField.hasDocValues()) {
      throw new IOException(schemaField + " must have DocValues to use this feature.");
    }
    boolean multiValued = schemaField.multiValued();
    FieldType fieldType = schemaField.getType();

    if (fieldType instanceof SortableTextField && schemaField.useDocValuesAsStored() == false) {
      throw new IOException(schemaField + " Must have useDocValuesAsStored='true' to be used with export writer");
    }

    if (fieldType instanceof IntValueFieldType) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
      } else {
        writers[i] = new IntFieldWriter(field);
      }
    } else if (fieldType instanceof LongValueFieldType) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
      } else {
        writers[i] = new LongFieldWriter(field);
      }
    } else if (fieldType instanceof FloatValueFieldType) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
      } else {
        writers[i] = new FloatFieldWriter(field);
      }
    } else if (fieldType instanceof DoubleValueFieldType) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
      } else {
        writers[i] = new DoubleFieldWriter(field);
      }
    } else if (fieldType instanceof StrField || fieldType instanceof SortableTextField) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
      } else {
        writers[i] = new StringFieldWriter(field, fieldType);
      }
    } else if (fieldType instanceof DateValueFieldType) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
      } else {
        writers[i] = new DateFieldWriter(field);
      }
    } else if (fieldType instanceof BoolField) {
      if (multiValued) {
        writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
      } else {
        writers[i] = new BoolFieldWriter(field, fieldType);
      }
    } else {
      throw new IOException("Export fields must be one of the following types: int,float,long,double,string,date,boolean,SortableText");
    }
  }
  return writers;
}
 
Example 19
Source File: TestSolrQueryParser.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
public void testFieldExistsQueries() throws SyntaxError {
  SolrQueryRequest req = req();
  String[] fieldSuffix = new String[] {
      "ti", "tf", "td", "tl", "tdt",
      "pi", "pf", "pd", "pl", "pdt",
      "i", "f", "d", "l", "dt", "s", "b",
      "is", "fs", "ds", "ls", "dts", "ss", "bs",
      "i_dv", "f_dv", "d_dv", "l_dv", "dt_dv", "s_dv", "b_dv",
      "is_dv", "fs_dv", "ds_dv", "ls_dv", "dts_dv", "ss_dv", "bs_dv",
      "i_dvo", "f_dvo", "d_dvo", "l_dvo", "dt_dvo",
      "t",
      "t_on", "b_norms", "s_norms", "dt_norms", "i_norms", "l_norms", "f_norms", "d_norms"
  };
  String[] existenceQueries = new String[] {
      "*", "[* TO *]"
  };

  for (String existenceQuery : existenceQueries) {
    for (String suffix : fieldSuffix) {
      IndexSchema indexSchema = h.getCore().getLatestSchema();
      String field = "foo_" + suffix;
      String query = field + ":" + existenceQuery;
      QParser qParser = QParser.getParser(query, req);
      Query createdQuery = qParser.getQuery();
      SchemaField schemaField = indexSchema.getField(field);

      // Test float & double realNumber queries differently
      if ("[* TO *]".equals(existenceQuery) && (schemaField.getType().getNumberType() == NumberType.DOUBLE || schemaField.getType().getNumberType() == NumberType.FLOAT)) {
        assertFalse("For float and double fields \"" + query + "\" is not an existence query, so the query returned should not be a DocValuesFieldExistsQuery.", createdQuery instanceof DocValuesFieldExistsQuery);
        assertFalse("For float and double fields \"" + query + "\" is not an existence query, so the query returned should not be a NormsFieldExistsQuery.", createdQuery instanceof NormsFieldExistsQuery);
        assertFalse("For float and double fields \"" + query + "\" is not an existence query, so NaN should not be matched via a ConstantScoreQuery.", createdQuery instanceof ConstantScoreQuery);
        assertFalse("For float and double fields\"" + query + "\" is not an existence query, so NaN should not be matched via a BooleanQuery (NaN and [* TO *]).", createdQuery instanceof BooleanQuery);
      } else {
        if (schemaField.hasDocValues()) {
          assertTrue("Field has docValues, so existence query \"" + query + "\" should return DocValuesFieldExistsQuery", createdQuery instanceof DocValuesFieldExistsQuery);
        } else if (!schemaField.omitNorms() && !schemaField.getType().isPointField()) { //TODO: Remove !isPointField() for SOLR-14199
          assertTrue("Field has norms and no docValues, so existence query \"" + query + "\" should return NormsFieldExistsQuery", createdQuery instanceof NormsFieldExistsQuery);
        } else if (schemaField.getType().getNumberType() == NumberType.DOUBLE || schemaField.getType().getNumberType() == NumberType.FLOAT) {
          assertTrue("PointField with NaN values must include \"exists or NaN\" if the field doesn't have norms or docValues: \"" + query + "\".", createdQuery instanceof ConstantScoreQuery);
          assertTrue("PointField with NaN values must include \"exists or NaN\" if the field doesn't have norms or docValues: \"" + query + "\".", ((ConstantScoreQuery)createdQuery).getQuery() instanceof BooleanQuery);
          assertEquals("PointField with NaN values must include \"exists or NaN\" if the field doesn't have norms or docValues: \"" + query + "\". This boolean query must be an OR.", 1, ((BooleanQuery)((ConstantScoreQuery)createdQuery).getQuery()).getMinimumNumberShouldMatch());
          assertEquals("PointField with NaN values must include \"exists or NaN\" if the field doesn't have norms or docValues: \"" + query + "\". This boolean query must have 2 clauses.", 2, ((BooleanQuery)((ConstantScoreQuery)createdQuery).getQuery()).clauses().size());
        } else {
          assertFalse("Field doesn't have docValues, so existence query \"" + query + "\" should not return DocValuesFieldExistsQuery", createdQuery instanceof DocValuesFieldExistsQuery);
          assertFalse("Field doesn't have norms, so existence query \"" + query + "\" should not return NormsFieldExistsQuery", createdQuery instanceof NormsFieldExistsQuery);
        }
      }
    }
  }
}
 
Example 20
Source File: RangeFacetRequest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public RangeFacetRequest(ResponseBuilder rb, String f) {
  super(rb, FacetParams.FACET_RANGE, f);

  IndexSchema schema = rb.req.getSchema();
  this.schemaField = schema.getField(facetOn);

  SolrParams params = SolrParams.wrapDefaults(localParams, rb.req.getParams());
  SolrParams required = new RequiredSolrParams(params);

  String methodStr = params.get(FacetParams.FACET_RANGE_METHOD);
  FacetParams.FacetRangeMethod method = (methodStr == null ? FacetParams.FacetRangeMethod.getDefault() : FacetParams.FacetRangeMethod.get(methodStr));

  if ((schemaField.getType() instanceof DateRangeField) && method.equals(FacetParams.FacetRangeMethod.DV)) {
    // the user has explicitly selected the FacetRangeMethod.DV method
    log.warn("Range facet method '{}' is not supported together with field type '{}'. Will use method '{}' instead"
        , FacetParams.FacetRangeMethod.DV, DateRangeField.class, FacetParams.FacetRangeMethod.FILTER);
    method = FacetParams.FacetRangeMethod.FILTER;
  }
  if (method.equals(FacetParams.FacetRangeMethod.DV) && !schemaField.hasDocValues() && (schemaField.getType().isPointField())) {
    log.warn("Range facet method '{}' is not supported on PointFields without docValues. Will use method '{}' instead"
        , FacetParams.FacetRangeMethod.DV
        , FacetParams.FacetRangeMethod.FILTER);
    method = FacetParams.FacetRangeMethod.FILTER;
  }

  this.start = required.getFieldParam(facetOn, FacetParams.FACET_RANGE_START);
  this.end = required.getFieldParam(facetOn, FacetParams.FACET_RANGE_END);


  this.gap = required.getFieldParam(facetOn, FacetParams.FACET_RANGE_GAP);
  this.minCount = params.getFieldInt(facetOn, FacetParams.FACET_MINCOUNT, 0);

  this.include = FacetParams.FacetRangeInclude.parseParam
      (params.getFieldParams(facetOn, FacetParams.FACET_RANGE_INCLUDE));

  this.hardEnd = params.getFieldBool(facetOn, FacetParams.FACET_RANGE_HARD_END, false);

  this.others = EnumSet.noneOf(FacetParams.FacetRangeOther.class);
  final String[] othersP = params.getFieldParams(facetOn, FacetParams.FACET_RANGE_OTHER);
  if (othersP != null && othersP.length > 0) {
    for (final String o : othersP) {
      others.add(FacetParams.FacetRangeOther.get(o));
    }
  }

  this.groupFacet = params.getBool(GroupParams.GROUP_FACET, false);
  if (groupFacet && method.equals(FacetParams.FacetRangeMethod.DV)) {
    // the user has explicitly selected the FacetRangeMethod.DV method
    log.warn("Range facet method '{}' is not supported together with '{}'. Will use method '{}' instead"
        , FacetParams.FacetRangeMethod.DV, GroupParams.GROUP_FACET, FacetParams.FacetRangeMethod.FILTER);
    method = FacetParams.FacetRangeMethod.FILTER;
  }

  this.method = method;

  RangeEndpointCalculator<? extends Comparable<?>> calculator = createCalculator();
  this.facetRanges = calculator.computeRanges();
  this.gapObj = calculator.getGap();
  this.startObj = calculator.getStart();
  this.endObj = calculator.getComputedEnd();
}