// Source returns the on-wire representation of the delete request,
// split into an action-and-meta-data line and an (optional) source line.
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html
// for details.
771695
func (r *BulkDeleteRequest) Source() ([]string, error) {
	if r.source != nil {
		return r.source, nil
	}
	command := bulkDeleteRequestCommand{
		"delete": bulkDeleteRequestCommandOp{
			Index:       r.index,
			Type:        r.typ,
			Id:          r.id,
			Routing:     r.routing,
			Parent:      r.parent,
			Version:     r.version,
			VersionType: r.versionType,
		},
	}

	var err error
	var body []byte
	if r.useEasyJSON {
		// easyjson
		body, err = command.MarshalJSON()
	} else {
		// encoding/json
		body, err = json.Marshal(command)
	}
	if err != nil {
		return nil, err
	}

	lines := []string{string(body)}
	r.source = lines

	return lines, nil
}
1326232
func (q *CompletionSuggester) Source(includeName bool) (interface{}, error) {
	cs := &completionSuggesterRequest{}

	if q.text != "" {
		cs.Text = q.text
	}
	if q.prefix != "" {
		cs.Prefix = q.prefix
	}
	if q.regex != "" {
		cs.Regex = q.regex
	}

	suggester := make(map[string]interface{})
	cs.Completion = suggester

	if q.analyzer != "" {
		suggester["analyzer"] = q.analyzer
	}
	if q.field != "" {
		suggester["field"] = q.field
	}
	if q.size != nil {
		suggester["size"] = *q.size
	}
	if q.shardSize != nil {
		suggester["shard_size"] = *q.shardSize
	}
	switch len(q.contextQueries) {
	case 0:
	case 1:
		src, err := q.contextQueries[0].Source()
		if err != nil {
			return nil, err
		}
		suggester["contexts"] = src
	default:
		ctxq := make(map[string]interface{})
		for _, query := range q.contextQueries {
			src, err := query.Source()
			if err != nil {
				return nil, err
			}
			// Merge the dictionary into ctxq
			m, ok := src.(map[string]interface{})
			if !ok {
				return nil, errors.New("elastic: context query is not a map")
			}
			for k, v := range m {
				ctxq[k] = v
			}
		}
		suggester["contexts"] = ctxq
	}

	// Fuzzy options
	if q.fuzzyOptions != nil {
		src, err := q.fuzzyOptions.Source()
		if err != nil {
			return nil, err
		}
		suggester["fuzzy"] = src
	}

	// Regex options
	if q.regexOptions != nil {
		src, err := q.regexOptions.Source()
		if err != nil {
			return nil, err
		}
		suggester["regex"] = src
	}

	if q.skipDuplicates != nil {
		suggester["skip_duplicates"] = *q.skipDuplicates
	}

	// TODO(oe) Add completion-suggester specific parameters here

	if !includeName {
		return cs, nil
	}

	source := make(map[string]interface{})
	source[q.name] = cs
	return source, nil
}
60938
func (q *RangeQuery) Source() (interface{}, error) {
	source := make(map[string]interface{})

	rangeQ := make(map[string]interface{})
	source["range"] = rangeQ

	params := make(map[string]interface{})
	rangeQ[q.name] = params

	params["from"] = q.from
	params["to"] = q.to
	if q.timeZone != "" {
		params["time_zone"] = q.timeZone
	}
	if q.format != "" {
		params["format"] = q.format
	}
	if q.relation != "" {
		params["relation"] = q.relation
	}
	if q.boost != nil {
		params["boost"] = *q.boost
	}
	params["include_lower"] = q.includeLower
	params["include_upper"] = q.includeUpper

	if q.queryName != "" {
		rangeQ["_name"] = q.queryName
	}

	return source, nil
}
635150
func (q QueryStringQuery) Source() interface{} {
	// {
	//    "query_string" : {
	//      "default_field" : "content",
	//      "query" : "this AND that OR thus"
	//    }
	// }

	source := make(map[string]interface{})

	query := make(map[string]interface{})
	source["query_string"] = query

	query["query"] = q.queryString

	if q.defaultField != "" {
		query["default_field"] = q.defaultField
	}

	if len(q.fields) > 0 {
		fields := make([]string, 0)
		for _, field := range q.fields {
			if boost, found := q.fieldBoosts[field]; found {
				if boost != nil {
					fields = append(fields, fmt.Sprintf("%s^%f", field, *boost))
				} else {
					fields = append(fields, field)
				}
			} else {
				fields = append(fields, field)
			}
		}
		query["fields"] = fields
	}

	if q.tieBreaker != nil {
		query["tie_breaker"] = *q.tieBreaker
	}

	if q.useDisMax != nil {
		query["use_dis_max"] = *q.useDisMax
	}

	if q.defaultOper != "" {
		query["default_operator"] = q.defaultOper
	}

	if q.analyzer != "" {
		query["analyzer"] = q.analyzer
	}

	if q.quoteAnalyzer != "" {
		query["quote_analyzer"] = q.quoteAnalyzer
	}

	if q.autoGeneratePhraseQueries != nil {
		query["auto_generate_phrase_queries"] = *q.autoGeneratePhraseQueries
	}

	if q.allowLeadingWildcard != nil {
		query["allow_leading_wildcard"] = *q.allowLeadingWildcard
	}

	if q.lowercaseExpandedTerms != nil {
		query["lowercase_expanded_terms"] = *q.lowercaseExpandedTerms
	}

	if q.enablePositionIncrements != nil {
		query["enable_position_increments"] = *q.enablePositionIncrements
	}

	if q.fuzzyMinSim != nil {
		query["fuzzy_min_sim"] = *q.fuzzyMinSim
	}

	if q.boost != nil {
		query["boost"] = *q.boost
	}

	if q.fuzzyPrefixLength != nil {
		query["fuzzy_prefix_length"] = *q.fuzzyPrefixLength
	}

	if q.fuzzyMaxExpansions != nil {
		query["fuzzy_max_expansions"] = *q.fuzzyMaxExpansions
	}

	if q.fuzzyRewrite != "" {
		query["fuzzy_rewrite"] = q.fuzzyRewrite
	}

	if q.phraseSlop != nil {
		query["phrase_slop"] = *q.phraseSlop
	}

	if q.analyzeWildcard != nil {
		query["analyze_wildcard"] = *q.analyzeWildcard
	}

	if q.rewrite != "" {
		query["rewrite"] = q.rewrite
	}

	if q.minimumShouldMatch != "" {
		query["minimum_should_match"] = q.minimumShouldMatch
	}

	if q.quoteFieldSuffix != "" {
		query["quote_field_suffix"] = q.quoteFieldSuffix
	}

	if q.lenient != nil {
		query["lenient"] = *q.lenient
	}

	return source
}
623618
func (fc *Flow) Source(name string, f func(io.Writer, *pb.InstructionStat) error) (ret *Dataset) {
	ret = fc.NewNextDataset(1)
	step := fc.AddOneToOneStep(nil, ret)
	step.IsOnDriverSide = true
	step.Name = name
	step.Function = func(readers []io.Reader, writers []io.Writer, stats *pb.InstructionStat) error {
		errChan := make(chan error, len(writers))
		for _, writer := range writers {
			go func(writer io.Writer) {
				errChan <- f(writer, stats)
			}(writer)
		}
		for range writers {
			err := <-errChan
			if err != nil {
				return err
			}
		}
		return nil
	}
	return
}
220567
func (q *SuggesterCategoryIndex) Source() (interface{}, error) {
	source := make(map[string]interface{})

	switch len(q.values) {
	case 0:
		source[q.name] = make([]string, 0)
	case 1:
		source[q.name] = q.values[0]
	default:
		source[q.name] = q.values
	}

	return source, nil
}
46739
func (q *ExistsQuery) Source() (interface{}, error) {
	// {
	//   "exists" : {
	//     "field" : "user"
	//   }
	// }

	query := make(map[string]interface{})
	params := make(map[string]interface{})
	query["exists"] = params

	params["field"] = q.name
	if q.queryName != "" {
		params["_name"] = q.queryName
	}

	return query, nil
}
1120779
func (q *BoolQuery) Source() (interface{}, error) {
	// {
	//	"bool" : {
	//		"must" : {
	//			"term" : { "user" : "kimchy" }
	//		},
	//		"must_not" : {
	//			"range" : {
	//				"age" : { "from" : 10, "to" : 20 }
	//			}
	//		},
	//    "filter" : [
	//      ...
	//    ]
	//		"should" : [
	//			{
	//				"term" : { "tag" : "wow" }
	//			},
	//			{
	//				"term" : { "tag" : "elasticsearch" }
	//			}
	//		],
	//		"minimum_should_match" : 1,
	//		"boost" : 1.0
	//	}
	// }

	query := make(map[string]interface{})

	boolClause := make(map[string]interface{})
	query["bool"] = boolClause

	// must
	if len(q.mustClauses) == 1 {
		src, err := q.mustClauses[0].Source()
		if err != nil {
			return nil, err
		}
		boolClause["must"] = src
	} else if len(q.mustClauses) > 1 {
		var clauses []interface{}
		for _, subQuery := range q.mustClauses {
			src, err := subQuery.Source()
			if err != nil {
				return nil, err
			}
			clauses = append(clauses, src)
		}
		boolClause["must"] = clauses
	}

	// must_not
	if len(q.mustNotClauses) == 1 {
		src, err := q.mustNotClauses[0].Source()
		if err != nil {
			return nil, err
		}
		boolClause["must_not"] = src
	} else if len(q.mustNotClauses) > 1 {
		var clauses []interface{}
		for _, subQuery := range q.mustNotClauses {
			src, err := subQuery.Source()
			if err != nil {
				return nil, err
			}
			clauses = append(clauses, src)
		}
		boolClause["must_not"] = clauses
	}

	// filter
	if len(q.filterClauses) == 1 {
		src, err := q.filterClauses[0].Source()
		if err != nil {
			return nil, err
		}
		boolClause["filter"] = src
	} else if len(q.filterClauses) > 1 {
		var clauses []interface{}
		for _, subQuery := range q.filterClauses {
			src, err := subQuery.Source()
			if err != nil {
				return nil, err
			}
			clauses = append(clauses, src)
		}
		boolClause["filter"] = clauses
	}

	// should
	if len(q.shouldClauses) == 1 {
		src, err := q.shouldClauses[0].Source()
		if err != nil {
			return nil, err
		}
		boolClause["should"] = src
	} else if len(q.shouldClauses) > 1 {
		var clauses []interface{}
		for _, subQuery := range q.shouldClauses {
			src, err := subQuery.Source()
			if err != nil {
				return nil, err
			}
			clauses = append(clauses, src)
		}
		boolClause["should"] = clauses
	}

	if q.boost != nil {
		boolClause["boost"] = *q.boost
	}
	if q.minimumShouldMatch != "" {
		boolClause["minimum_should_match"] = q.minimumShouldMatch
	}
	if q.adjustPureNegative != nil {
		boolClause["adjust_pure_negative"] = *q.adjustPureNegative
	}
	if q.queryName != "" {
		boolClause["_name"] = q.queryName
	}

	return query, nil
}
645571
func (q CompletionSuggester) Source(includeName bool) interface{} {
	cs := &completionSuggesterRequest{}

	if q.text != "" {
		cs.Text = q.text
	}

	suggester := make(map[string]interface{})
	cs.Completion = suggester

	if q.analyzer != "" {
		suggester["analyzer"] = q.analyzer
	}
	if q.field != "" {
		suggester["field"] = q.field
	}
	if q.size != nil {
		suggester["size"] = *q.size
	}
	if q.shardSize != nil {
		suggester["shard_size"] = *q.shardSize
	}
	switch len(q.contextQueries) {
	case 0:
	case 1:
		suggester["context"] = q.contextQueries[0].Source()
	default:
		ctxq := make([]interface{}, 0)
		for _, query := range q.contextQueries {
			ctxq = append(ctxq, query.Source())
		}
		suggester["context"] = ctxq
	}

	// TODO(oe) Add competion-suggester specific parameters here

	if !includeName {
		return cs
	}

	source := make(map[string]interface{})
	source[q.name] = cs
	return source
}
391317
func (s *SearchSource) Source() interface{} {
	source := make(map[string]interface{})

	if s.from != -1 {
		source["from"] = s.from
	}
	if s.size != -1 {
		source["size"] = s.size
	}
	if s.timeout != "" {
		source["timeout"] = s.timeout
	}
	if s.query != nil {
		source["query"] = s.query.Source()
	}
	if s.postFilter != nil {
		source["post_filter"] = s.postFilter.Source()
	}
	if s.minScore != nil {
		source["min_score"] = *s.minScore
	}
	if s.version != nil {
		source["version"] = *s.version
	}
	if s.explain != nil {
		source["explain"] = *s.explain
	}
	if s.fetchSourceContext != nil {
		source["_source"] = s.fetchSourceContext.Source()
	}

	if s.fieldNames != nil {
		switch len(s.fieldNames) {
		case 1:
			source["fields"] = s.fieldNames[0]
		default:
			source["fields"] = s.fieldNames
		}
	}

	if len(s.fieldDataFields) > 0 {
		source["fielddata_fields"] = s.fieldDataFields
	}

	if len(s.partialFields) > 0 {
		pfmap := make(map[string]interface{})
		for _, partialField := range s.partialFields {
			pfmap[partialField.Name] = partialField.Source()
		}
		source["partial_fields"] = pfmap
	}

	if len(s.scriptFields) > 0 {
		sfmap := make(map[string]interface{})
		for _, scriptField := range s.scriptFields {
			sfmap[scriptField.FieldName] = scriptField.Source()
		}
		source["script_fields"] = sfmap
	}

	if len(s.sorters) > 0 {
		sortarr := make([]interface{}, 0)
		for _, sorter := range s.sorters {
			sortarr = append(sortarr, sorter.Source())
		}
		source["sort"] = sortarr
	} else if len(s.sorts) > 0 {
		sortarr := make([]interface{}, 0)
		for _, sort := range s.sorts {
			sortarr = append(sortarr, sort.Source())
		}
		source["sort"] = sortarr
	}

	if s.trackScores {
		source["track_scores"] = s.trackScores
	}

	if len(s.indexBoosts) > 0 {
		source["indices_boost"] = s.indexBoosts
	}

	if len(s.facets) > 0 {
		facetsMap := make(map[string]interface{})
		for field, facet := range s.facets {
			facetsMap[field] = facet.Source()
		}
		source["facets"] = facetsMap
	}

	if len(s.aggregations) > 0 {
		aggsMap := make(map[string]interface{})
		for name, aggregate := range s.aggregations {
			aggsMap[name] = aggregate.Source()
		}
		source["aggregations"] = aggsMap
	}

	if s.highlight != nil {
		source["highlight"] = s.highlight.Source()
	}

	if len(s.suggesters) > 0 {
		suggesters := make(map[string]interface{})
		for _, s := range s.suggesters {
			suggesters[s.Name()] = s.Source(false)
		}
		if s.globalSuggestText != "" {
			suggesters["text"] = s.globalSuggestText
		}
		source["suggest"] = suggesters
	}

	if len(s.rescores) > 0 {
		// Strip empty rescores from request
		rescores := make([]*Rescore, 0)
		for _, r := range s.rescores {
			if !r.IsEmpty() {
				rescores = append(rescores, r)
			}
		}

		if len(rescores) == 1 {
			rescores[0].defaultRescoreWindowSize = s.defaultRescoreWindowSize
			source["rescore"] = rescores[0].Source()
		} else {
			slice := make([]interface{}, 0)
			for _, r := range rescores {
				r.defaultRescoreWindowSize = s.defaultRescoreWindowSize
				slice = append(slice, r.Source())
			}
			source["rescore"] = slice
		}
	}

	if len(s.stats) > 0 {
		source["stats"] = s.stats
	}

	if len(s.innerHits) > 0 {
		// Top-level inner hits
		// See http://www.elastic.co/guide/en/elasticsearch/reference/1.5/search-request-inner-hits.html#top-level-inner-hits
		// "inner_hits": {
		//   "<inner_hits_name>": {
		//     "<path|type>": {
		//       "<path-to-nested-object-field|child-or-parent-type>": {
		//         <inner_hits_body>,
		//         [,"inner_hits" : { [<sub_inner_hits>]+ } ]?
		//       }
		//     }
		//   },
		//   [,"<inner_hits_name_2>" : { ... } ]*
		// }
		m := make(map[string]interface{})
		for name, hit := range s.innerHits {
			if hit.path != "" {
				path := make(map[string]interface{})
				path[hit.path] = hit.Source()
				m[name] = map[string]interface{}{
					"path": path,
				}
			} else if hit.typ != "" {
				typ := make(map[string]interface{})
				typ[hit.typ] = hit.Source()
				m[name] = map[string]interface{}{
					"type": typ,
				}
			} else {
				// TODO the Java client throws here, because either path or typ must be specified
			}
		}
		source["inner_hits"] = m
	}

	return source
}
1246341
func (q *SuggesterCategoryQuery) Source() (interface{}, error) {
	source := make(map[string]interface{})

	switch len(q.values) {
	case 0:
		source[q.name] = make([]string, 0)
	default:
		contexts := make([]interface{}, 0)
		for val, boost := range q.values {
			context := make(map[string]interface{})
			context["context"] = val
			if boost != nil {
				context["boost"] = *boost
			}
			contexts = append(contexts, context)
		}
		source[q.name] = contexts
	}

	return source, nil
}
1012465
func (q *CommonTermsQuery) Source() (interface{}, error) {
	//  {
	//    "common": {
	//      "body": {
	//        "query":            "this is bonsai cool",
	//        "cutoff_frequency": 0.001
	//      }
	//    }
	//  }
	source := make(map[string]interface{})
	body := make(map[string]interface{})
	query := make(map[string]interface{})

	source["common"] = body
	body[q.name] = query
	query["query"] = q.text

	if q.cutoffFreq != nil {
		query["cutoff_frequency"] = *q.cutoffFreq
	}
	if q.highFreq != nil {
		query["high_freq"] = *q.highFreq
	}
	if q.highFreqOp != "" {
		query["high_freq_operator"] = q.highFreqOp
	}
	if q.lowFreq != nil {
		query["low_freq"] = *q.lowFreq
	}
	if q.lowFreqOp != "" {
		query["low_freq_operator"] = q.lowFreqOp
	}
	if q.lowFreqMinimumShouldMatch != "" || q.highFreqMinimumShouldMatch != "" {
		mm := make(map[string]interface{})
		if q.lowFreqMinimumShouldMatch != "" {
			mm["low_freq"] = q.lowFreqMinimumShouldMatch
		}
		if q.highFreqMinimumShouldMatch != "" {
			mm["high_freq"] = q.highFreqMinimumShouldMatch
		}
		query["minimum_should_match"] = mm
	}
	if q.analyzer != "" {
		query["analyzer"] = q.analyzer
	}
	if q.boost != nil {
		query["boost"] = *q.boost
	}
	if q.queryName != "" {
		query["_name"] = q.queryName
	}

	return source, nil
}
1144125
func (a *MovFnAggregation) Source() (interface{}, error) {
	source := make(map[string]interface{})
	params := make(map[string]interface{})
	source["moving_fn"] = params

	// Add buckets paths
	switch len(a.bucketsPaths) {
	case 0:
	case 1:
		params["buckets_path"] = a.bucketsPaths[0]
	default:
		params["buckets_path"] = a.bucketsPaths
	}

	// Script
	if a.script != nil {
		src, err := a.script.Source()
		if err != nil {
			return nil, err
		}
		params["script"] = src
	}

	if a.format != "" {
		params["format"] = a.format
	}
	if a.gapPolicy != "" {
		params["gap_policy"] = a.gapPolicy
	}
	params["window"] = a.window

	// Add Meta data if available
	if len(a.meta) > 0 {
		source["meta"] = a.meta
	}

	return source, nil
}
47907
func (q TemplateQuery) Source() interface{} {
	// {
	//   "template" : {
	//     "query" : {"match_{{template}}": {}},
	//     "params" : {
	//       "template": "all"
	//     }
	//   }
	// }

	query := make(map[string]interface{})

	tmpl := make(map[string]interface{})
	query["template"] = tmpl

	// TODO(oe): Implementation differs from online documentation at http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-template-query.html
	var fieldname string
	switch q.templateType {
	case "file": // file
		fieldname = "file"
	case "indexed", "id": // indexed
		fieldname = "id"
	default: // inline
		fieldname = "query"
	}

	tmpl[fieldname] = q.template
	if len(q.vars) > 0 {
		tmpl["params"] = q.vars
	}

	return query
}
86154
func (q MatchAllQuery) Source() interface{} {
	// {
	//   "match_all" : { ... }
	// }
	source := make(map[string]interface{})
	params := make(map[string]interface{})
	source["match_all"] = params
	if q.boost != nil {
		params["boost"] = q.boost
	}
	if q.normsField != "" {
		params["norms_field"] = q.normsField
	}
	return source
}
620970
func (q *TermQuery) Source() (interface{}, error) {
	// {"term":{"name":"value"}}
	source := make(map[string]interface{})
	tq := make(map[string]interface{})
	source["term"] = tq

	if q.boost == nil && q.queryName == "" {
		tq[q.name] = q.value
	} else {
		subQ := make(map[string]interface{})
		subQ["value"] = q.value
		if q.boost != nil {
			subQ["boost"] = *q.boost
		}
		if q.queryName != "" {
			subQ["_name"] = q.queryName
		}
		tq[q.name] = subQ
	}
	return source, nil
}
1278264
func (r *BulkUpdateRequest) Source() ([]string, error) {
	// { "update" : { "_index" : "test", "_type" : "type1", "_id" : "1", ... } }
	// { "doc" : { "field1" : "value1", ... } }
	// or
	// { "update" : { "_index" : "test", "_type" : "type1", "_id" : "1", ... } }
	// { "script" : { ... } }

	if r.source != nil {
		return r.source, nil
	}

	lines := make([]string, 2)

	// "update" ...
	updateCommand := bulkUpdateRequestCommandOp{
		Index:           r.index,
		Type:            r.typ,
		Id:              r.id,
		Routing:         r.routing,
		Parent:          r.parent,
		Version:         r.version,
		VersionType:     r.versionType,
		RetryOnConflict: r.retryOnConflict,
	}
	command := bulkUpdateRequestCommand{
		"update": updateCommand,
	}

	var err error
	var body []byte
	if r.useEasyJSON {
		// easyjson
		body, err = command.MarshalJSON()
	} else {
		// encoding/json
		body, err = json.Marshal(command)
	}
	if err != nil {
		return nil, err
	}

	lines[0] = string(body)

	// 2nd line: {"doc" : { ... }} or {"script": {...}}
	var doc interface{}
	if r.doc != nil {
		// Automatically serialize strings as raw JSON
		switch t := r.doc.(type) {
		default:
			doc = r.doc
		case string:
			if len(t) > 0 {
				doc = json.RawMessage(t)
			}
		case *string:
			if t != nil && len(*t) > 0 {
				doc = json.RawMessage(*t)
			}
		}
	}
	data := bulkUpdateRequestCommandData{
		DocAsUpsert:    r.docAsUpsert,
		DetectNoop:     r.detectNoop,
		Upsert:         r.upsert,
		ScriptedUpsert: r.scriptedUpsert,
		Doc:            doc,
		Source:         r.returnSource,
	}
	if r.script != nil {
		script, err := r.script.Source()
		if err != nil {
			return nil, err
		}
		data.Script = script
	}

	if r.useEasyJSON {
		// easyjson
		body, err = data.MarshalJSON()
	} else {
		// encoding/json
		body, err = json.Marshal(data)
	}
	if err != nil {
		return nil, err
	}

	lines[1] = string(body)

	r.source = lines
	return lines, nil
}