@Override
  public Mapper parse(ParseContext context) throws IOException {
    QueryShardContext queryShardContext = new QueryShardContext(this.queryShardContext);
    if (context.doc().getField(queryBuilderField.name()) != null) {
      // If a percolator query has been defined in an array object then multiple percolator queries
      // could be provided. In order to prevent this we fail if we try to parse more than one query
      // for the current document.
      throw new IllegalArgumentException("a document can only contain one percolator query");
    }

    XContentParser parser = context.parser();
    QueryBuilder queryBuilder =
        parseQueryBuilder(queryShardContext.newParseContext(parser), parser.getTokenLocation());
    verifyQuery(queryBuilder);
    // Fetching of terms, shapes and indexed scripts happen during this rewrite:
    queryBuilder = queryBuilder.rewrite(queryShardContext);

    try (XContentBuilder builder = XContentFactory.contentBuilder(QUERY_BUILDER_CONTENT_TYPE)) {
      queryBuilder.toXContent(builder, new MapParams(Collections.emptyMap()));
      builder.flush();
      byte[] queryBuilderAsBytes = BytesReference.toBytes(builder.bytes());
      context
          .doc()
          .add(
              new Field(
                  queryBuilderField.name(), queryBuilderAsBytes, queryBuilderField.fieldType()));
    }

    Query query = toQuery(queryShardContext, mapUnmappedFieldAsString, queryBuilder);
    processQuery(query, context);
    return null;
  }
 @Override
 public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
   builder.startObject();
   if (docBuilder != null) {
     docBuilder.toXContent(builder, params);
   }
   if (queryBuilder != null) {
     builder.field("query");
     queryBuilder.toXContent(builder, params);
   }
   if (size != null) {
     builder.field("size", size);
   }
   if (sorts != null) {
     builder.startArray("sort");
     for (SortBuilder<?> sort : sorts) {
       sort.toXContent(builder, params);
     }
     builder.endArray();
   }
   if (trackScores != null) {
     builder.field("track_scores", trackScores);
   }
   if (highlightBuilder != null) {
     builder.field(SearchSourceBuilder.HIGHLIGHT_FIELD.getPreferredName(), highlightBuilder);
   }
   if (aggregationBuilders != null || pipelineAggregationBuilders != null) {
     builder.field("aggregations");
     builder.startObject();
     if (aggregationBuilders != null) {
       for (AggregatorBuilder<?> aggregation : aggregationBuilders) {
         aggregation.toXContent(builder, params);
       }
     }
     if (pipelineAggregationBuilders != null) {
       for (PipelineAggregatorBuilder<?> aggregation : pipelineAggregationBuilders) {
         aggregation.toXContent(builder, params);
       }
     }
     builder.endObject();
   }
   builder.endObject();
   return builder;
 }