// Source returns JSON for the query.
975721
func (q *ScriptQuery) Source() (interface{}, error) {
	if q.script == nil {
		return nil, errors.New("ScriptQuery expected a script")
	}
	source := make(map[string]interface{})
	params := make(map[string]interface{})
	source["script"] = params

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

	if q.queryName != "" {
		params["_name"] = q.queryName
	}
	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
}
615417
func (q *ContextSuggester) Source(includeName bool) (interface{}, error) {
	cs := &contextSuggesterRequest{}

	if q.prefix != "" {
		cs.Prefix = q.prefix
	}

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

	if q.field != "" {
		suggester["field"] = q.field
	}
	if q.size != nil {
		suggester["size"] = *q.size
	}
	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
	}

	if !includeName {
		return cs, nil
	}

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

	if len(q.precision) == 0 {
		if q.location != nil {
			source[q.name] = q.location.Source()
		}
	} else {
		x := make(map[string]interface{})
		source[q.name] = x

		if q.location != nil {
			x["value"] = q.location.Source()
		}

		switch len(q.precision) {
		case 0:
		case 1:
			x["precision"] = q.precision[0]
		default:
			x["precision"] = q.precision
		}
	}

	return source
}
287216
func (s *NestedSort) Source() (interface{}, error) {
	source := make(map[string]interface{})

	if s.path != "" {
		source["path"] = s.path
	}
	if s.filter != nil {
		src, err := s.filter.Source()
		if err != nil {
			return nil, err
		}
		source["filter"] = src
	}
	if s.nestedSort != nil {
		src, err := s.nestedSort.Source()
		if err != nil {
			return nil, err
		}
		source["nested"] = src
	}

	return source, nil
}
574687
func (s *Script) Source() (interface{}, error) {
	if s.typ == "" && s.lang == "" && len(s.params) == 0 {
		return s.script, nil
	}
	source := make(map[string]interface{})
	// Beginning with 6.0, the type can only be "source" or "id"
	if s.typ == "" || s.typ == "inline" {
		src, err := s.rawScriptSource(s.script)
		if err != nil {
			return nil, err
		}
		source["source"] = src
	} else {
		source["id"] = s.script
	}
	if s.lang != "" {
		source["lang"] = s.lang
	}
	if len(s.params) > 0 {
		source["params"] = s.params
	}
	return source, nil
}
457999
func (fn RandomFunction) Source() interface{} {
	source := make(map[string]interface{})
	if fn.seed != nil {
		source["seed"] = fn.seed
	}
	// Notice that the weight has to be serialized in FunctionScoreQuery.
	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
}
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
}
436728
func (q FuzzyLikeThisFieldQuery) Source() interface{} {
	// {
	//	"fuzzy_like_this_field" : {
	//    "name.first": {
	//      "like_text" : "text like this one",
	//      "max_query_terms" : 12
	//    }
	// }

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

	query := make(map[string]interface{})
	source["fuzzy_like_this_field"] = query
	fq := make(map[string]interface{})
	query[q.field] = fq

	fq["like_text"] = q.likeText

	if q.maxQueryTerms != nil {
		fq["max_query_terms"] = *q.maxQueryTerms
	}
	if q.fuzziness != nil {
		fq["fuzziness"] = q.fuzziness
	}
	if q.prefixLength != nil {
		fq["prefix_length"] = *q.prefixLength
	}
	if q.ignoreTF != nil {
		fq["ignore_tf"] = *q.ignoreTF
	}
	if q.boost != nil {
		fq["boost"] = *q.boost
	}
	if q.analyzer != "" {
		fq["analyzer"] = q.analyzer
	}
	if q.failOnUnsupportedField != nil {
		fq["fail_on_unsupported_field"] = *q.failOnUnsupportedField
	}
	if q.queryName != "" {
		fq["_name"] = q.queryName
	}

	return source
}
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
}
1123308
func (q *HasParentQuery) Source() (interface{}, error) {
	// {
	//   "has_parent" : {
	//       "parent_type" : "blog",
	//       "query" : {
	//           "term" : {
	//               "tag" : "something"
	//           }
	//       }
	//   }
	// }
	source := make(map[string]interface{})
	query := make(map[string]interface{})
	source["has_parent"] = query

	src, err := q.query.Source()
	if err != nil {
		return nil, err
	}
	query["query"] = src
	query["parent_type"] = q.parentType
	if q.boost != nil {
		query["boost"] = *q.boost
	}
	if q.score != nil {
		query["score"] = *q.score
	}
	if q.queryName != "" {
		query["_name"] = q.queryName
	}
	if q.innerHit != nil {
		src, err := q.innerHit.Source()
		if err != nil {
			return nil, err
		}
		query["inner_hits"] = src
	}
	if q.ignoreUnmapped != nil {
		query["ignore_unmapped"] = *q.ignoreUnmapped
	}
	return source, nil
}
1067118
func (q FilteredQuery) Source() interface{} {
	// {
	//     "filtered" : {
	//         "query" : {
	//             "term" : { "tag" : "wow" }
	//         },
	//         "filter" : {
	//             "range" : {
	//                 "age" : { "from" : 10, "to" : 20 }
	//             }
	//         }
	//     }
	// }

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

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

	filtered["query"] = q.query.Source()

	if len(q.filters) == 1 {
		filtered["filter"] = q.filters[0].Source()
	} else if len(q.filters) > 1 {
		filter := make(map[string]interface{})
		filtered["filter"] = filter
		and := make(map[string]interface{})
		filter["and"] = and
		filters := make([]interface{}, 0)
		for _, f := range q.filters {
			filters = append(filters, f.Source())
		}
		and["filters"] = filters
		/*
			anded := make([]map[string]interface{}, 0)
			filtered["filter"] = anded
			for _, f := range q.filters {
				andElem := make(map[string]interface{})
				andElem["and"] = f.Source()
				anded = append(anded, andElem)
			}
		*/
	}

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

	return source
}
847653
func (q DisMaxQuery) Source() interface{} {
	// {
	//  "dis_max" : {
	//    "tie_breaker" : 0.7,
	//    "boost" : 1.2,
	//    "queries" : {
	//      {
	//        "term" : { "age" : 34 }
	//      },
	//      {
	//        "term" : { "age" : 35 }
	//      }
	//    ]
	//  }
	// }

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

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

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

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

	// queries
	clauses := make([]interface{}, 0)
	for _, subQuery := range q.queries {
		clauses = append(clauses, subQuery.Source())
	}
	disMax["queries"] = clauses

	return query
}
404769
func (sh *ScriptSignificanceHeuristic) Source() (interface{}, error) {
	source := make(map[string]interface{})
	if sh.script != nil {
		src, err := sh.script.Source()
		if err != nil {
			return nil, err
		}
		source["script"] = src
	}
	return source, nil
}
206952
func (s *ScriptSort) Source() (interface{}, error) {
	if s.script == nil {
		return nil, errors.New("ScriptSort expected a script")
	}
	source := make(map[string]interface{})
	x := make(map[string]interface{})
	source["_script"] = x

	src, err := s.script.Source()
	if err != nil {
		return nil, err
	}
	x["script"] = src

	x["type"] = s.typ

	if s.ascending {
		x["order"] = "asc"
	} else {
		x["order"] = "desc"
	}
	if s.sortMode != nil {
		x["mode"] = *s.sortMode
	}
	if s.nestedFilter != nil {
		src, err := s.nestedFilter.Source()
		if err != nil {
			return nil, err
		}
		x["nested_filter"] = src
	}
	if s.nestedPath != nil {
		x["nested_path"] = *s.nestedPath
	}
	if s.nestedSort != nil {
		src, err := s.nestedSort.Source()
		if err != nil {
			return nil, err
		}
		x["nested"] = src
	}
	return source, nil
}