Serialize the search to a structure as passed for a search body.
162367
def serialize(self):
        """"""
        res = {}
        if self.query:
            if isinstance(self.query, dict):
                res["query"] = self.query
            elif isinstance(self.query, Query):
                res["query"] = self.query.serialize()
            else:
                raise InvalidQuery("Invalid query")
        if self.filter:
            res['filter'] = self.filter.serialize()
        if self.facet.facets:
            res['facets'] = self.facet.serialize()
        if self.agg.aggs:
            res['aggs'] = self.agg.serialize()
        if self.rescore:
            res['rescore'] = self.rescore.serialize()
        if self.window_size:
            res['window_size'] = self.window_size
        if self.fields is not None: #Deal properly with self.fields = []
            res['fields'] = self.fields
        if self.size is not None:
            res['size'] = self.size
        if self.start is not None:
            res['from'] = self.start
        if self._highlight:
            res['highlight'] = self._highlight.serialize()
        if self.sort:
            if isinstance(self.sort, SortFactory):
                sort = self.sort.serialize()
                if sort:
                    res['sort'] = sort
            else:
                res['sort'] = self.sort
        if self.explain:
            res['explain'] = self.explain
        if self.version:
            res['version'] = self.version
        if self.track_scores:
            res['track_scores'] = self.track_scores
        if self._script_fields:
            if isinstance(self.script_fields, ScriptFields):
                res['script_fields'] = self.script_fields.serialize()
            elif isinstance(self.script_fields, dict):
                res['script_fields'] = self.script_fields
            else:
                raise ScriptFieldsError("Parameter script_fields should of type ScriptFields or dict")
        if self.index_boost:
            res['indices_boost'] = self.index_boost
        if self.min_score:
            res['min_score'] = self.min_score
        if self.stats:
            res['stats'] = self.stats
        if self.partial_fields:
            res['partial_fields'] = self.partial_fields
        if self._source:
            res['_source'] = self._source
        if self.timeout:
            res['timeout'] = self.timeout
        return res
572158
private function dumpStructure() {
    dump("Requesters:");
    dump($this->requesters);

    dump("Request roots:");
    dump($this->requestRoots);

    dump("Request paths:");
    dump($this->requestPaths);

    dump("Local names:");
    dump($this->localNames);

    if (isset($this->tree)) {
      dump("Containment tree:");
      dump($this->tree);
    }
  }
246047
def put(index_name, doc_type, identifier, body, force, verbose):
    """"""
    result = current_search_client.index(
        index=index_name,
        doc_type=doc_type or index_name,
        id=identifier,
        body=json.load(body),
        op_type='index' if force or identifier is None else 'create',
    )
    if verbose:
        click.echo(json.dumps(result))
1163973
def _serialize(self):
        
        result = { a: getattr(self, a) for a in type(self).properties
            if type(self).properties[a].mutable }

        for k, v in result.items():
            if isinstance(v, Base):
                result[k] = v.id

        return result
1212451
def serialize(self):
        """"""
        # Serialize fields to a dict
        data = {}
        for field_name in self:
            value = self._values.get(field_name)
            field = self.fields.get(field_name)
            if value is not None:
                if field.all:
                    value = [field.serialize(v) for v in value]
                else:
                    value = field.serialize(value)
            # Skip empty fields unless field.null
            if not field.null and ((field.all and value == []) or (not field.all and value in {None, ''})):
                continue
            data[field.name] = value
        return data
1199394
private String _serializeStruct(Struct struct, Map<Object, String> done, String id) throws ConverterException {
	StringBuilder sb = new StringBuilder(goIn() + "<STRUCT ID=\"" + id + "\">");

	Iterator<Key> it = struct.keyIterator();

	deep++;
	while (it.hasNext()) {
	    Key key = it.next();
	    // <ENTRY NAME="STRING" TYPE="STRING">hello</ENTRY>
	    String value = _serialize(struct.get(key, null), done);
	    sb.append(goIn() + "<ENTRY NAME=\"" + key.toString() + "\" TYPE=\"" + type + "\">");
	    sb.append(value);
	    sb.append(goIn() + "</ENTRY>");
	}
	deep--;

	sb.append(goIn() + "</STRUCT>");
	type = "STRUCT";
	return sb.toString();
    }
867546
def _serialize_data(self, data):
        """"""
        if self.request and self.request.query_params.get('hydrate_data', False):
            serializer = DataSerializer(data, many=True, read_only=True)
            serializer.bind('data', self)
            return serializer.data
        else:
            return [d.id for d in data]
551759
def _serialize_object(self, response_data, request):
        
        if self._is_doc_request(request):
            return response_data
        else:
            return super(DocumentedResource, self)._serialize_object(
                response_data, request)
843355
private void _serialize(PageContext pc, Set test, Object object, StringBuilder sb, boolean serializeQueryByColumns, Set done) throws ConverterException {

	// NULL
	if (object == null || object == NULL) {
	    sb.append(goIn());
	    sb.append("null");
	    return;
	}
	// String
	if (object instanceof String || object instanceof StringBuilder) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(object.toString(), '"', charsetEncoder));
	    return;
	}
	// TimeZone
	if (object instanceof TimeZone) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(((TimeZone) object).getID(), '"', charsetEncoder));
	    return;
	}
	// Locale
	if (object instanceof Locale) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(LocaleFactory.toString((Locale) object), '"', charsetEncoder));
	    return;
	}
	// Character
	if (object instanceof Character) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(String.valueOf(((Character) object).charValue()), '"', charsetEncoder));
	    return;
	}
	// Number
	if (object instanceof Number) {
	    sb.append(goIn());
	    sb.append(Caster.toString(((Number) object)));
	    return;
	}
	// Boolean
	if (object instanceof Boolean) {
	    sb.append(goIn());
	    sb.append(Caster.toString(((Boolean) object).booleanValue()));
	    return;
	}
	// DateTime
	if (object instanceof DateTime) {
	    _serializeDateTime((DateTime) object, sb);
	    return;
	}
	// Date
	if (object instanceof Date) {
	    _serializeDate((Date) object, sb);
	    return;
	}
	// XML
	if (object instanceof Node) {
	    _serializeXML((Node) object, sb);
	    return;
	}
	// Timespan
	if (object instanceof TimeSpan) {
	    _serializeTimeSpan((TimeSpan) object, sb);
	    return;
	}
	// File
	if (object instanceof File) {
	    _serialize(pc, test, ((File) object).getAbsolutePath(), sb, serializeQueryByColumns, done);
	    return;
	}
	// String Converter
	if (object instanceof ScriptConvertable) {
	    sb.append(((ScriptConvertable) object).serialize());
	    return;
	}
	// byte[]
	if (object instanceof byte[]) {
	    sb.append("\"" + Base64Coder.encode((byte[]) object) + "\"");
	    return;
	}
1169568
def put_templates(self, ignore=None):
        """"""
        ignore = ignore or []

        def _replace_prefix(template_path, body):
            """Replace index prefix in template request body."""
            pattern = '__SEARCH_INDEX_PREFIX__'

            prefix = self.app.config['SEARCH_INDEX_PREFIX'] or ''
            if prefix:
                assert pattern in body, "You are using the prefix `{0}`, "
                "but the template `{1}` does not contain the "
                "pattern `{2}`.".format(prefix, template_path, pattern)

            return body.replace(pattern, prefix)

        def _put_template(template):
            """Put template in search client."""
            with open(self.templates[template], 'r') as fp:
                body = fp.read()
                replaced_body = _replace_prefix(self.templates[template], body)
                return self.templates[template],\
                    current_search_client.indices.put_template(
                        name=template,
                        body=json.loads(replaced_body),
                        ignore=ignore,
                )

        for template in self.templates:
            yield _put_template(template)
1226274
def serialize(self):
        """"""
        data = {'doc': self.doc}
        if isinstance(self.query, Query):
            data['query'] = self.query.serialize()
        return data
318813
def serialize(self, submit=None):
        
        include_fields = prepare_fields(self.fields, self.submit_fields, submit)
        return Payload.from_fields(include_fields)
574995
def to_dict(self, search_fields=None):
        """"""
        fields = self._fields
        if search_fields == 'update':
            fields = self._search_for_update_fields
        elif search_fields == 'all':
            fields = self._all_searchable_fields
        elif search_fields == 'exclude':
            # exclude search fields for update actions,
            # but include updateable_search_fields
            fields = [field for field in self._fields
                      if field in self._updateable_search_fields or
                      field not in self._search_for_update_fields]

        return {field: self.field_to_dict(field) for field in fields
                if getattr(self, field, None) is not None}
1133753
def flatten_json_request_body(prefix, dict_body, spec):
    """"""
    if len(spec) == 1 and 'type' in spec:
        return {prefix: to_str(dict_body, spec)}

    flat = {}
    for key, value in dict_body.items():
        node_type = spec[key]['type']
        if node_type == 'list':
            for idx, v in enumerate(value, 1):
                pref = key + '.member.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref, v, spec[key]['member']))
        elif node_type == 'map':
            for idx, (k, v) in enumerate(value.items(), 1):
                pref = key + '.entry.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref + '.key', k, spec[key]['key']))
                flat.update(flatten_json_request_body(
                    pref + '.value', v, spec[key]['value']))
        else:
            flat.update(flatten_json_request_body(key, value, spec[key]))

    if prefix:
        prefix = prefix + '.'
    return dict((prefix + k, v) for k, v in flat.items())
1300373
public void serialize(@Nonnull Iterable<QueryResult> results, @Nonnull OutputStream out) throws IOException {
		JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
		g.writeStartObject();
		g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
		g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
		g.writeArrayFieldStart("data");

		for (QueryResult metric : results) {
			g.writeStartObject();
			g.writeStringField("name", metric.getName());
			if (instanceId != null && !instanceId.isEmpty()) {
				g.writeStringField("instance", instanceId);
			}
			g.writeNumberField("collected_at", metric.getEpoch(TimeUnit.SECONDS));
			if (metric.getValue() instanceof Integer) {
				g.writeNumberField("value", (Integer) metric.getValue());
			} else if (metric.getValue() instanceof Long) {
				g.writeNumberField("value", (Long) metric.getValue());
			} else if (metric.getValue() instanceof Float) {
				g.writeNumberField("value", (Float) metric.getValue());
			} else if (metric.getValue() instanceof Double) {
				g.writeNumberField("value", (Double) metric.getValue());
			}
			g.writeEndObject();
		}

		g.writeEndArray();
		g.writeEndObject();
		g.flush();
		g.close();
	}
986303
def serialize(
            self,
            value,  # type: Any
            state  # type: _ProcessorState
    ):
        # type: (...) -> ET.Element
        """"""
        if self._nested is None:
            state.raise_error(InvalidRootProcessor,
                              'Cannot directly serialize a non-nested array "{}"'
                              .format(self.alias))

        if not value and self.required:
            state.raise_error(MissingValue, 'Missing required array: "{}"'.format(
                self.alias))

        start_element, end_element = _element_path_create_new(self._nested)
        self._serialize(end_element, value, state)

        return start_element
1019450
def serialize(self, data):
        

        super(Serializer, self).serialize(data)

        body = {
            'jsonapi': {
                'version': goldman.config.JSONAPI_VERSION,
            },
            'links': {
                'self': self.req.path,
            },
            'meta': {
                'included_count': 0,
                'primary_count': 0,
                'total_primary': self.req.pages.total,
            },
        }

        included = data['included']
        if included:
            body['included'] = self._serialize_datas(included)
            body['meta']['included_count'] = len(included)

        _data = data['data']
        if isinstance(_data, list):
            body.update({'data': self._serialize_datas(_data)})
            body.update({'links': self._serialize_pages()})
            body['meta']['primary_count'] = len(_data)
        elif _data:
            body.update({'data': self._serialize_data(_data)})
            body['meta']['primary_count'] = 1
        else:
            body.update({'data': None})

        self.resp.body = json.dumps(body)