Implements a multivalued field facet on the results.

        This is implemented using brute force - O(N^2) -
        because Xapian does not have it implemented yet
        (see http://trac.xapian.org/ticket/199)
971059
def _do_multivalued_field_facets(self, results, field_facets):
        
        facet_dict = {}

        for field in field_facets:
            facet_list = {}
            if not self._multi_value_field(field):
                continue

            for result in results:
                field_value = getattr(result, field)
                for item in field_value:  # Facet each item in a MultiValueField
                    facet_list[item] = facet_list.get(item, 0) + 1

            facet_dict[field] = list(facet_list.items())
        return facet_dict
92934
def get_fields(self):
        
        field_mapping = OrderedDict()
        for field, data in self.instance.items():
            field_mapping.update(
                {field: self.facet_dict_field_class(
                    child=self.facet_list_field_class(child=self.facet_field_serializer_class(data)), required=False)}
            )

        if self.serialize_objects is True:
            field_mapping["objects"] = serializers.SerializerMethodField()

        return field_mapping
510774
def get_vals(self, field, goids=None):
        """"""
        go2nt = self.go2nt
        if goids is None:
            goids = set(go2nt)
        return [getattr(go2nt[go], field) for go in goids]
365158
function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
			var url = host + 'databases/' + db + '/facets/' + indexName + '?';
			url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
			url += '&facetStart=0&facetPageSize=1024';
			var facets = fieldsToSum
				.map(function (field) {
					return {
						"Mode": 0,
						"Aggregation": 16,
						"AggregationField": field,
						"Name": groupBy,
						"DisplayName": field,
						"Ranges": [],
						"MaxResults": null,
						"TermSortMode": 0,
						"IncludeRemainingTerms": false
					};
				});
			url += '&facets=' + JSON.stringify(facets);
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
970853
def get_values(self, data, filter_values):
        
        values = super(ModelTermsFacet, self).get_values(data, filter_values)
        ids = [key for (key, doc_count, selected) in values]
        # Perform a model resolution: models are feched from DB
        # We use model field to cast IDs
        ids = [self.model_field.to_mongo(id) for id in ids]
        objects = self.model.objects.in_bulk(ids)

        return [
            (objects.get(self.model_field.to_mongo(key)), doc_count, selected)
            for (key, doc_count, selected) in values
        ]
588679
function (values, schema, options, callback) {
    var newValues = {}
        , errors = []
        , modelList = find(schema)
        , val;

    for (var model in modelList) {
        if (_.isArray(modelList[model])) {

            if (values === undefined) {
                val = undefined;
            }
            else {
                val = values[model];
            }

            // Empty array defined in schema
            if (_.isEmpty(modelList[model])) {
                if (val) {
                    newValues[model] = val;
                }
            }
            else {
                // Set value to empty array if empty given
                if (val == undefined) {
                    if (options && options.partial == true) {
                        // Do nothing
                    }
                    else {
                        newValues[model] = [];
                    }
                }
                else {
                    // Sub model defined in schema
                    for (var thisSubSchema in modelList[model]) {
                        if (_.isArray(val)) {
                            for (var thisValue in val) {

                                // Check if type array or plain array
                                if (typeof val[thisValue] == "object") {
                                    modelCompare(val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors = _.union(errors, err);
                                        }
                                        if (data !== null) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                                else {
                                    rulesMatch(thisValue, val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors.push(err);
                                        }
                                        if (data !== undefined) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            modelCompare(val, modelList[model][thisSubSchema], options, function (err, data) {
                                if (err) {
                                    errors = _.union(errors, err);
                                }
                                if (data !== null) {
                                    newValues[model] = data;
                                }
                            });
                        }
                    }
                }
            }
        } else {
            // Check for definition of {} in model to allow any data for this node without validation
            if (_.isEmpty(modelList[model])) {
                for (var index in values) {
                    var filter = new RegExp("^" + model);
                    if (index.match(filter)) {
                        newValues[index] = values[index];
                    }
                }
            }
            else {
                if (values === undefined) {
                    val = undefined;
                }
                else {
                    val = values[model];
                }

                rulesMatch(model, val, modelList[model], options, function (err, data) {
                    if (err) {
                        errors.push(err);
                    }
                    if (data !== undefined) {
                        newValues[model] = data;
                    }
                });
            }
        }
    }

    if (_.isEmpty(errors)) {
        errors = null;
    }
    else {
        errors = {name: 'ValidationError', err: errors};
    }
    if (_.isEmpty(newValues)) {
        newValues = null;
    }
    callback(errors, newValues);
}
1014606
def find(context, facet_name, *args)
      facet = find_facet(context, facet_name)

      if !facet
        return nil
      end

      case result = facet.find(*args)
      when Array
        result.map { |item| @entities[item] }
      when String
        @entities[result]
      when NilClass
        nil
      else
        raise "Bad facet return type #{result.class.name.dump}"
      end
    end
695811
private void validateFacetFields(String[] facetFieldList) {
        if(facetFieldList == null || facetFieldList.length == 0){
            return;
        }
        for (String facetfield : facetFieldList){
            if(schema.getColumnIndex(facetfield) < 0){
                throw new IllegalArgumentException("Facet field:"+facetfield+", not found in schema");
            }
        }

    }
475552
private static Object generateValue(Field field) {
    Class<?> rawType = field.getType();

    //TODO Objects other than Lists might need parametrized types.
    if (List.class.isAssignableFrom(rawType)) {
      ParameterizedType genericType = (ParameterizedType) field.getGenericType();
      return createListObject(genericType);
    }

    return generateValue(rawType);
  }
379170
private Map<String, Object> parseFacet(String facet) throws Exception {
        Map<String, Object> outputMap = new HashMap<>();
        if (facet.contains(AGGREGATION_IDENTIFIER)) {
            // Validate function
            for (String function : AGGREGATION_FUNCTIONS) {
                if (facet.startsWith(function)) {
                    return null;
                }
            }
            throw new Exception("Invalid aggregation function: " + facet);
        } else if (facet.contains(RANGE_IDENTIFIER)) {
            // Deal with ranges...
            int numMatches = StringUtils.countMatches(facet, ':');
            if (numMatches > 1) {
                // Special case: facet with type "query" and with a nested "range"
                String[] split = facet.split(":");
                Map<String, Object> rangeMap = new HashMap<>();
                StringBuilder filter = new StringBuilder(split[3]);
                for (int i = 4; i < split.length; i++) {
                    filter.append(":").append(split[i]);
                }

                String[] range = split[0].replace("[", ":").replace("..", ":").replace("]", "").split(":");
                rangeMap.put("field", range[0]);
                rangeMap.put("type", "range");
                rangeMap.put("start", parseNumber(range[1]));
                rangeMap.put("end", parseNumber(range[2]));
                rangeMap.put("step", parseNumber(split[1]));

                String[] nested = split[2].split(LABEL_SEPARATOR);
                outputMap.put("field", nested[0]);
                outputMap.put("type", "query");
                outputMap.put("q", filter.toString());
                if (nested.length > 1) {
                    Map<String, Object> nestedMap = new HashMap<>();
                    nestedMap.put("field", nested[1]);
                    nestedMap.put("type", "terms");
                    Map<String, Object> auxMap1 = new HashMap<>();
                    auxMap1.put(range[0], rangeMap);
                    nestedMap.put("facet", auxMap1);

                    Map<String, Object> auxMap2 = new HashMap<>();
                    auxMap2.put(nested[1], nestedMap);
                    outputMap.put("facet", auxMap2);
                } else {
                    Map<String, Object> auxMap1 = new HashMap<>();
                    auxMap1.put(range[0], rangeMap);
                    outputMap.put("facet", auxMap1);
                }
            } else {
                String[] split = facet.replace("[", ":").replace("..", ":").replace("]", "").split(":");
                outputMap.put("field", split[0]);
                outputMap.put("start", parseNumber(split[1]));
                outputMap.put("end", parseNumber(split[2]));
                outputMap.put("step", parseNumber(split[3]));
            }
        } else {
            // Categorical...
            Matcher matcher = CATEGORICAL_PATTERN.matcher(facet);
            if (matcher.find()) {
                boolean isQuery = false;
                outputMap.put("field", matcher.group(1));
                String include = matcher.group(2);
                if (StringUtils.isNotEmpty(include)) {
                    include = include.replace("]", "").replace("[", "");
                    if (include.endsWith("*")) {
                        outputMap.put("prefix", include.substring(0, include.indexOf("*")));
                    } else {
                        isQuery = true;
                        List<String> filters = new ArrayList<>();
                        for (String value: include.split(INCLUDE_SEPARATOR)) {
                            filters.add(matcher.group(1) + ":" + value);
                        }
                        outputMap.put("q", StringUtils.join(filters, " OR "));
                    }
                }

                if (isQuery) {
                    outputMap.put("type", "query");

                    Map<String, Object> auxMap = new HashMap<>();
                    auxMap.put("field", matcher.group(1));
                    auxMap.put("type", "terms");
                    setTermLimit(matcher.group(3), auxMap);

                    Map<String, Object> tmpMap = new HashMap<>();
                    tmpMap.put(matcher.group(1), auxMap);

                    outputMap.put("facet", tmpMap);
                } else {
                    outputMap.put("type", "terms");
                    setTermLimit(matcher.group(3), outputMap);
                }
            } else {
                throw new Exception("Invalid categorical facet: " + facet);
            }
        }

        return outputMap;
    }
361698
protected void appendFacetOption(StringBuffer query, final String name, final String value) {

        query.append(" facet.").append(name).append("=").append(value);
    }
1138407
private String buildCsvValue(final Field field,
                                 final String fieldValue) {


        return (areTextValuesWrapped && field.getType().equals(String.class)
                || isValueWrappable.test(fieldValue))
                ? wrapWithQuotes(fieldValue)
                : fieldValue;
    }
544755
def relationnal_result(method_name, *arguments)
      self.class.reload_fields_definition(false)
      if self.class.many2one_associations.has_key?(method_name)
        load_m2o_association(method_name, *arguments)
      elsif self.class.polymorphic_m2o_associations.has_key?(method_name)# && @associations[method_name]
        load_polymorphic_m2o_association(method_name, *arguments)
#        values = @associations[method_name].split(',')
#        self.class.const_get(values[0]).find(values[1], arguments.extract_options!)
      else # o2m or m2m
        load_x2m_association(method_name, *arguments)
      end
    end
406086
def json_facet(self, field=None):
        '''
        
        '''
        facets = self.data['facets']
        if field is None:
            temp_fields = [x for x in facets.keys() if x != 'count']
            if len(temp_fields) != 1:
                raise ValueError("field argument not specified and it looks like there is more than one field in facets. Specify the field to get json.facet from. ")
            field = temp_fields[0]

        if field not in self.data['facets']:
            raise ValueError("Facet Field {} Not found in response, available fields are {}".format(
                                        field, self.data['facets'].keys() ))
        return self.data['facets'][field]
1146105
def evaluate_result(self, m):
        ''''''
        # ok, figure the fixed fields we've pulled out and type convert them
        fixed_fields = list(m.groups())
        for n in self._fixed_fields:
            if n in self._type_conversions:
                fixed_fields[n] = self._type_conversions[n](fixed_fields[n], m)
        fixed_fields = tuple(fixed_fields[n] for n in self._fixed_fields)

        # grab the named fields, converting where requested
        groupdict = m.groupdict()
        named_fields = {}
        name_map = {}
        for k in self._named_fields:
            korig = self._group_to_name_map[k]
            name_map[korig] = k
            if k in self._type_conversions:
                value = self._type_conversions[k](groupdict[k], m)
            else:
                value = groupdict[k]

            named_fields[korig] = value

        # now figure the match spans
        spans = dict((n, m.span(name_map[n])) for n in named_fields)
        spans.update((i, m.span(n + 1))
            for i, n in enumerate(self._fixed_fields))

        # and that's our result
        return Result(fixed_fields, self._expand_named_fields(named_fields), spans)
500467
private void addSubDimension(final Facets _facets,
                                 final DimValue _dimValue,
                                 final String _dim,
                                 final String _path)
        throws IOException
    {
        final FacetResult result = _facets.getTopChildren(1000, _dim, _path);
        if (result != null) {
            LOG.debug("FacetResult {}.", result);
            for (final LabelAndValue labelValue : result.labelValues) {
                final DimValue dimValue = new DimValue().setLabel(labelValue.label)
                                .setValue(labelValue.value.intValue());
                dimValue.setPath(ArrayUtils.addAll(_dimValue.getPath(), result.path));
                _dimValue.getChildren().add(dimValue);
                addSubDimension(_facets, dimValue, _dim, _path + "/" + labelValue.label);
            }
        }
    }
948299
def solr_names_and_values(field_name, field_value, index_types)
      return {} if field_value.nil?
      
      # Determine the set of index types
      index_types = Array(index_types)
      index_types.uniq!
      index_types.dup.each do |index_type|
        if index_type.to_s =~ /^not_(.*)/
          index_types.delete index_type # not_foo
          index_types.delete $1.to_sym  # foo
        end
      end
      
      # Map names and values
      
      results = {}

      # Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
      field_value = [field_value] if field_value.kind_of? Time
      
      index_types.each do |index_type|
        Array(field_value).each do |single_value|
          # Get mapping for field
          descriptor = indexer(index_type)
          data_type = extract_type(single_value)
          name, converter = descriptor.name_and_converter(field_name, type: data_type)
          next unless name

          # Is there a custom converter?
          # TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.

          value = if converter
            if converter.arity == 1
              converter.call(single_value)
            else
              converter.call(single_value, field_name)
            end
          elsif data_type == :boolean
            single_value
          else
            single_value.to_s
          end
          
          # Add mapped name & value, unless it's a duplicate
          if descriptor.evaluate_suffix(data_type).multivalued?
            values = (results[name] ||= [])
            values << value unless value.nil? || values.include?(value)
          else
            Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
            results[name] = value
          end
        end
      end
        
      results
    end