summaryrefslogtreecommitdiffstats
path: root/vendor/gopkg.in
diff options
context:
space:
mode:
authorChristopher Speller <crspeller@gmail.com>2018-04-16 05:37:14 -0700
committerJoram Wilander <jwawilander@gmail.com>2018-04-16 08:37:14 -0400
commit6e2cb00008cbf09e556b00f87603797fcaa47e09 (patch)
tree3c0eb55ff4226a3f024aad373140d1fb860a6404 /vendor/gopkg.in
parentbf24f51c4e1cc6286885460672f7f449e8c6f5ef (diff)
downloadchat-6e2cb00008cbf09e556b00f87603797fcaa47e09.tar.gz
chat-6e2cb00008cbf09e556b00f87603797fcaa47e09.tar.bz2
chat-6e2cb00008cbf09e556b00f87603797fcaa47e09.zip
Depenancy upgrades and movign to dep. (#8630)
Diffstat (limited to 'vendor/gopkg.in')
-rw-r--r--vendor/gopkg.in/alexcesaro/quotedprintable.v3/encodedword_test.go281
-rw-r--r--vendor/gopkg.in/alexcesaro/quotedprintable.v3/reader_test.go200
-rw-r--r--vendor/gopkg.in/alexcesaro/quotedprintable.v3/writer_test.go154
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/ber_test.go168
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/header_test.go135
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/identifier_test.go344
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/length_test.go191
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/suite_test.go182
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc1.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc10.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc11.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc12.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc13.berbin11 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc14.berbin7 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc15.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc16.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc17.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc18.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc19.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc2.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc20.berbin11 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc21.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc22.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc23.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc24.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc25.berbin5 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc26.berbin5 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc27.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc28.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc29.berbin3 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc3.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc30.berbin5 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc31.berbin4 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc32.berbin2 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc33.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc34.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc35.berbin16 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc36.berbin20 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc37.berbin14 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc38.berbin16 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc39.berbin2 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc4.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc40.berbin2 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc41.berbin16 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc42.berbin14 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc43.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc44.berbin2 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc45.berbin2 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc46.berbin11 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc47.berbin16 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc48.berbin16 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc5.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc6.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc7.ber1
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc8.berbin5 -> 0 bytes
-rw-r--r--vendor/gopkg.in/asn1-ber.v1/tests/tc9.ber1
-rw-r--r--vendor/gopkg.in/gomail.v2/auth_test.go156
-rw-r--r--vendor/gopkg.in/gomail.v2/example_test.go215
-rw-r--r--vendor/gopkg.in/gomail.v2/message_test.go630
-rw-r--r--vendor/gopkg.in/gomail.v2/send_test.go80
-rw-r--r--vendor/gopkg.in/gomail.v2/smtp_test.go254
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/.travis.yml7
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/CHANGELOG-6.0.md18
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/CONTRIBUTORS2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ISSUE_TEMPLATE.md1
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/README.md80
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/acknowledged_response.go4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/backoff_test.go140
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request.go16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_easyjson.go74
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_test.go79
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_index_request.go35
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_easyjson.go66
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_test.go116
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_processor.go3
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_processor_test.go425
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_test.go600
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_update_request.go33
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_easyjson.go126
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_test.go149
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/canonicalize_test.go72
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/clear_scroll.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/clear_scroll_test.go87
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/client.go110
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/client_test.go1319
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster-test/Makefile16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster-test/README.md63
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster-test/cluster-test.go361
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_health.go10
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_health_test.go119
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_state.go20
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_state_test.go93
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_stats.go18
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/cluster_stats_test.go92
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/config/config_test.go45
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/count.go23
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/count_test.go127
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/decoder_test.go50
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/delete.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/delete_by_query.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/delete_by_query_test.go146
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/delete_template.go109
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/delete_test.go134
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/errors_test.go295
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/etc/elasticsearch.yml15
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/etc/ingest-geoip/.gitkeep0
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/etc/jvm.options100
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/etc/log4j2.properties74
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/etc/scripts/.gitkeep0
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/example_test.go530
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/exists.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/exists_test.go53
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/explain.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/explain_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/fetch_source_context.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/fetch_source_context_test.go125
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/field_caps.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/field_caps_test.go146
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/field_stats.go259
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/geo_point_test.go24
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/get.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/get_template.go113
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/get_test.go166
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/highlight.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/highlight_test.go211
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/index.go15
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/index_test.go280
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_analyze.go15
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_analyze_test.go85
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_close.go14
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_close_test.go84
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_create.go18
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_create_test.go63
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_delete.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_delete_template.go16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_delete_test.go23
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists_template.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists_template_test.go68
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists_test.go23
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists_type.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_exists_type_test.go135
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_flush.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_flush_test.go70
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge.go10
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge_test.go57
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases_test.go181
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping_test.go55
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping_test.go50
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_settings.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_settings_test.go82
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_template.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_template_test.go41
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_get_test.go98
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_open.go16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_open_test.go23
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_alias.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_alias_test.go222
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping_test.go95
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_settings.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_settings_test.go95
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_put_template.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_refresh.go10
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_refresh_test.go81
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_rollover.go15
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_rollover_test.go116
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_segments.go15
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_segments_test.go86
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_shrink.go18
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_shrink_test.go34
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_stats.go39
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/indices_stats_test.go86
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline.go16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline_test.go31
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline_test.go121
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline_test.go31
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline_test.go35
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/inner_hit_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/mget.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/mget_test.go96
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/msearch.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/msearch_test.go303
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/mtermvectors.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/mtermvectors_test.go134
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/nodes_info.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/nodes_info_test.go43
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/nodes_stats.go45
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/nodes_stats_test.go138
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/percolate_test.go68
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ping.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/ping_test.go65
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/plugins_test.go32
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/put_template.go145
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_insert/bulk_insert.go173
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_processor/main.go149
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/recipes/connect/connect.go43
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/recipes/sliced_scroll/sliced_scroll.go161
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/reindex.go24
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/reindex_test.go401
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/request.go53
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/request_test.go72
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/response_test.go48
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/retrier_test.go174
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/retry_test.go44
-rwxr-xr-xvendor/gopkg.in/olivere/elastic.v5/run-es.sh4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/script.go35
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/script_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/scroll.go20
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/scroll_test.go387
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search.go40
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs.go263
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_adjacency_matrix.go96
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children_test.go46
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite.go498
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite_test.go92
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_count_thresholds.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram_test.go49
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range_test.go155
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_diversified_sampler.go126
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter_test.go66
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters_test.go99
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance_test.go93
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geohash_grid_test.go84
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range_test.go90
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested_test.go62
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range_test.go178
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested_test.go83
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler_test.go30
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms.go18
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms_test.go211
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text.go245
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text_test.go66
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_terms_test.go155
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats_test.go53
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality_test.go78
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_centroid.go95
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks_test.go78
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles_test.go78
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits_test.go31
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count_test.go63
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script_test.go30
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector_test.go29
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg.go14
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg_test.go132
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_test.go903
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_aggs_test.go3416
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder_test.go29
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_bool.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_bool_test.go33
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting_test.go30
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms_test.go85
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max_test.go28
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_exists.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_exists_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_score_funcs.go28
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_test.go166
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box_test.go63
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance_test.go69
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon_test.go58
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child_test.go45
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_ids.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_ids_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_indices.go89
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_test.go29
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_match_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this.go24
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this_test.go92
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match_test.go131
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_nested.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_nested_test.go86
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id_test.go52
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator_test.go65
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_example_test.go35
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_test.go45
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string.go109
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string_test.go46
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_range.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_range_test.go68
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_raw_string_test.go44
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp_test.go47
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_script.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_script_test.go45
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string_test.go87
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_slice.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_slice_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_term.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_term_test.go46
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_terms.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set.go96
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set_test.go75
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_test.go82
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_type.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_type_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard_test.go68
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_request.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_request_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_shards.go180
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_source.go8
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_source_test.go295
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_suggester_test.go355
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup.go2
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup_test.go27
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/search_test.go1320
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/setup_test.go445
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_create.go13
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository_test.go61
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_create_test.go63
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository.go16
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository_test.go35
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository_test.go39
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository_test.go31
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/sort.go123
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/sort_test.go278
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggest.go158
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggest_field.go4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggest_field_test.go29
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_completion.go24
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_completion_fuzzy.go181
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_completion_test.go110
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context.go4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context_category.go4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context_category_test.go163
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo.go4
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo_test.go48
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_context_test.go55
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_phrase.go14
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_phrase_test.go169
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_term.go6
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/suggester_term_test.go49
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_cancel.go10
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_cancel_test.go51
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_get_task.go8
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_get_task_test.go43
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_list.go12
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/tasks_list_test.go65
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/termvectors.go17
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/termvectors_test.go157
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/update.go26
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/update_by_query.go11
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/update_by_query_test.go147
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/update_integration_test.go58
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/update_test.go262
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/uritemplates/utils_test.go105
-rw-r--r--vendor/gopkg.in/olivere/elastic.v5/validate.go280
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/.travis.yml18
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/Makefile2
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/README.md83
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/deprecated_test.go59
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/doc.go2
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/example_test.go103
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/http_test.go99
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/rate.go17
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/rate_test.go128
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/deprecated.go32
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore.go2
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore_test.go40
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore.go168
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore_test.go85
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/storetest/doc.go2
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/store/storetest/storetest.go176
-rw-r--r--vendor/gopkg.in/throttled/throttled.v2/varyby_test.go58
-rw-r--r--vendor/gopkg.in/yaml.v2/.travis.yml3
-rw-r--r--vendor/gopkg.in/yaml.v2/NOTICE13
-rw-r--r--vendor/gopkg.in/yaml.v2/README.md2
-rw-r--r--vendor/gopkg.in/yaml.v2/apic.go55
-rw-r--r--vendor/gopkg.in/yaml.v2/decode.go238
-rw-r--r--vendor/gopkg.in/yaml.v2/decode_test.go1032
-rw-r--r--vendor/gopkg.in/yaml.v2/emitterc.go5
-rw-r--r--vendor/gopkg.in/yaml.v2/encode.go136
-rw-r--r--vendor/gopkg.in/yaml.v2/encode_test.go501
-rw-r--r--vendor/gopkg.in/yaml.v2/example_embedded_test.go41
-rw-r--r--vendor/gopkg.in/yaml.v2/go.mod5
-rw-r--r--vendor/gopkg.in/yaml.v2/readerc.go20
-rw-r--r--vendor/gopkg.in/yaml.v2/resolve.go80
-rw-r--r--vendor/gopkg.in/yaml.v2/scannerc.go29
-rw-r--r--vendor/gopkg.in/yaml.v2/sorter.go9
-rw-r--r--vendor/gopkg.in/yaml.v2/suite_test.go12
-rw-r--r--vendor/gopkg.in/yaml.v2/writerc.go65
-rw-r--r--vendor/gopkg.in/yaml.v2/yaml.go123
-rw-r--r--vendor/gopkg.in/yaml.v2/yamlh.go30
479 files changed, 3616 insertions, 33080 deletions
diff --git a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/encodedword_test.go b/vendor/gopkg.in/alexcesaro/quotedprintable.v3/encodedword_test.go
deleted file mode 100644
index 368794fe7..000000000
--- a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/encodedword_test.go
+++ /dev/null
@@ -1,281 +0,0 @@
-package quotedprintable
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "strings"
- "testing"
-)
-
-func ExampleWordEncoder_Encode() {
- fmt.Println(QEncoding.Encode("utf-8", "¡Hola, señor!"))
- fmt.Println(QEncoding.Encode("utf-8", "Hello!"))
- fmt.Println(BEncoding.Encode("UTF-8", "¡Hola, señor!"))
- fmt.Println(QEncoding.Encode("ISO-8859-1", "Caf\xE9"))
- // Output:
- // =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=
- // Hello!
- // =?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?=
- // =?ISO-8859-1?q?Caf=E9?=
-}
-
-func ExampleWordDecoder_Decode() {
- dec := new(WordDecoder)
- header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
- if err != nil {
- panic(err)
- }
- fmt.Println(header)
-
- dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
- switch charset {
- case "x-case":
- // Fake character set for example.
- // Real use would integrate with packages such
- // as code.google.com/p/go-charset
- content, err := ioutil.ReadAll(input)
- if err != nil {
- return nil, err
- }
- return bytes.NewReader(bytes.ToUpper(content)), nil
- }
- return nil, fmt.Errorf("unhandled charset %q", charset)
- }
- header, err = dec.Decode("=?x-case?q?hello!?=")
- if err != nil {
- panic(err)
- }
- fmt.Println(header)
- // Output:
- // ¡Hola, señor!
- // HELLO!
-}
-
-func ExampleWordDecoder_DecodeHeader() {
- dec := new(WordDecoder)
- header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= <eric@example.org>, =?utf-8?q?Ana=C3=AFs?= <anais@example.org>")
- if err != nil {
- panic(err)
- }
- fmt.Println(header)
-
- header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=")
- if err != nil {
- panic(err)
- }
- fmt.Println(header)
-
- dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
- switch charset {
- case "x-case":
- // Fake character set for example.
- // Real use would integrate with packages such
- // as code.google.com/p/go-charset
- content, err := ioutil.ReadAll(input)
- if err != nil {
- return nil, err
- }
- return bytes.NewReader(bytes.ToUpper(content)), nil
- }
- return nil, fmt.Errorf("unhandled charset %q", charset)
- }
- header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=")
- if err != nil {
- panic(err)
- }
- fmt.Println(header)
- // Output:
- // Éric <eric@example.org>, Anaïs <anais@example.org>
- // ¡Hola, señor!
- // HELLO WORLD!
-}
-
-func TestEncodeWord(t *testing.T) {
- utf8, iso88591 := "utf-8", "iso-8859-1"
- tests := []struct {
- enc WordEncoder
- charset string
- src, exp string
- }{
- {QEncoding, utf8, "François-Jérôme", "=?utf-8?q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?="},
- {BEncoding, utf8, "Café", "=?utf-8?b?Q2Fmw6k=?="},
- {QEncoding, iso88591, "La Seleção", "=?iso-8859-1?q?La_Sele=C3=A7=C3=A3o?="},
- {QEncoding, utf8, "", ""},
- {QEncoding, utf8, "A", "A"},
- {QEncoding, iso88591, "a", "a"},
- {QEncoding, utf8, "123 456", "123 456"},
- {QEncoding, utf8, "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~", "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~"},
- }
-
- for _, test := range tests {
- if s := test.enc.Encode(test.charset, test.src); s != test.exp {
- t.Errorf("Encode(%q) = %q, want %q", test.src, s, test.exp)
- }
- }
-}
-
-func TestDecodeWord(t *testing.T) {
- tests := []struct {
- src, exp string
- hasErr bool
- }{
- {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!", false},
- {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme", false},
- {"=?UTF-8?q?ascii?=", "ascii", false},
- {"=?utf-8?B?QW5kcsOp?=", "André", false},
- {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont", false},
- {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" <jose@example.org>`, false},
- {"=?UTF-8?A?Test?=", "", true},
- {"=?UTF-8?Q?A=B?=", "", true},
- {"=?UTF-8?Q?=A?=", "", true},
- {"=?UTF-8?A?A?=", "", true},
- }
-
- for _, test := range tests {
- dec := new(WordDecoder)
- s, err := dec.Decode(test.src)
- if test.hasErr && err == nil {
- t.Errorf("Decode(%q) should return an error", test.src)
- continue
- }
- if !test.hasErr && err != nil {
- t.Errorf("Decode(%q): %v", test.src, err)
- continue
- }
- if s != test.exp {
- t.Errorf("Decode(%q) = %q, want %q", test.src, s, test.exp)
- }
- }
-}
-
-func TestDecodeHeader(t *testing.T) {
- tests := []struct {
- src, exp string
- }{
- {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!"},
- {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme"},
- {"=?UTF-8?q?ascii?=", "ascii"},
- {"=?utf-8?B?QW5kcsOp?=", "André"},
- {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont"},
- {"Jean", "Jean"},
- {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" <jose@example.org>`},
- {"=?UTF-8?A?Test?=", "=?UTF-8?A?Test?="},
- {"=?UTF-8?Q?A=B?=", "=?UTF-8?Q?A=B?="},
- {"=?UTF-8?Q?=A?=", "=?UTF-8?Q?=A?="},
- {"=?UTF-8?A?A?=", "=?UTF-8?A?A?="},
- // Incomplete words
- {"=?", "=?"},
- {"=?UTF-8?", "=?UTF-8?"},
- {"=?UTF-8?=", "=?UTF-8?="},
- {"=?UTF-8?Q", "=?UTF-8?Q"},
- {"=?UTF-8?Q?", "=?UTF-8?Q?"},
- {"=?UTF-8?Q?=", "=?UTF-8?Q?="},
- {"=?UTF-8?Q?A", "=?UTF-8?Q?A"},
- {"=?UTF-8?Q?A?", "=?UTF-8?Q?A?"},
- // Tests from RFC 2047
- {"=?ISO-8859-1?Q?a?=", "a"},
- {"=?ISO-8859-1?Q?a?= b", "a b"},
- {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"},
- {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"},
- {"=?ISO-8859-1?Q?a?= \r\n\t =?ISO-8859-1?Q?b?=", "ab"},
- {"=?ISO-8859-1?Q?a_b?=", "a b"},
- }
-
- for _, test := range tests {
- dec := new(WordDecoder)
- s, err := dec.DecodeHeader(test.src)
- if err != nil {
- t.Errorf("DecodeHeader(%q): %v", test.src, err)
- }
- if s != test.exp {
- t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, s, test.exp)
- }
- }
-}
-
-func TestCharsetDecoder(t *testing.T) {
- tests := []struct {
- src string
- want string
- charsets []string
- content []string
- }{
- {"=?utf-8?b?Q2Fmw6k=?=", "Café", nil, nil},
- {"=?ISO-8859-1?Q?caf=E9?=", "café", nil, nil},
- {"=?US-ASCII?Q?foo_bar?=", "foo bar", nil, nil},
- {"=?utf-8?Q?=?=", "=?utf-8?Q?=?=", nil, nil},
- {"=?utf-8?Q?=A?=", "=?utf-8?Q?=A?=", nil, nil},
- {
- "=?ISO-8859-15?Q?f=F5=F6?= =?windows-1252?Q?b=E0r?=",
- "f\xf5\xf6b\xe0r",
- []string{"iso-8859-15", "windows-1252"},
- []string{"f\xf5\xf6", "b\xe0r"},
- },
- }
-
- for _, test := range tests {
- i := 0
- dec := &WordDecoder{
- CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
- if charset != test.charsets[i] {
- t.Errorf("DecodeHeader(%q), got charset %q, want %q", test.src, charset, test.charsets[i])
- }
- content, err := ioutil.ReadAll(input)
- if err != nil {
- t.Errorf("DecodeHeader(%q), error in reader: %v", test.src, err)
- }
- got := string(content)
- if got != test.content[i] {
- t.Errorf("DecodeHeader(%q), got content %q, want %q", test.src, got, test.content[i])
- }
- i++
-
- return strings.NewReader(got), nil
- },
- }
- got, err := dec.DecodeHeader(test.src)
- if err != nil {
- t.Errorf("DecodeHeader(%q): %v", test.src, err)
- }
- if got != test.want {
- t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, got, test.want)
- }
- }
-}
-
-func TestCharsetDecoderError(t *testing.T) {
- dec := &WordDecoder{
- CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
- return nil, errors.New("Test error")
- },
- }
-
- if _, err := dec.DecodeHeader("=?charset?Q?foo?="); err == nil {
- t.Error("DecodeHeader should return an error")
- }
-}
-
-func BenchmarkQEncodeWord(b *testing.B) {
- for i := 0; i < b.N; i++ {
- QEncoding.Encode("UTF-8", "¡Hola, señor!")
- }
-}
-
-func BenchmarkQDecodeWord(b *testing.B) {
- dec := new(WordDecoder)
-
- for i := 0; i < b.N; i++ {
- dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
- }
-}
-
-func BenchmarkQDecodeHeader(b *testing.B) {
- dec := new(WordDecoder)
-
- for i := 0; i < b.N; i++ {
- dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
- }
-}
diff --git a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/reader_test.go b/vendor/gopkg.in/alexcesaro/quotedprintable.v3/reader_test.go
deleted file mode 100644
index 01ba8f75b..000000000
--- a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/reader_test.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package quotedprintable
-
-import (
- "bufio"
- "bytes"
- "errors"
- "flag"
- "fmt"
- "io"
- "os/exec"
- "regexp"
- "sort"
- "strings"
- "testing"
- "time"
-)
-
-func TestReader(t *testing.T) {
- tests := []struct {
- in, want string
- err interface{}
- }{
- {in: "", want: ""},
- {in: "foo bar", want: "foo bar"},
- {in: "foo bar=3D", want: "foo bar="},
- {in: "foo bar=3d", want: "foo bar="}, // lax.
- {in: "foo bar=\n", want: "foo bar"},
- {in: "foo bar\n", want: "foo bar\n"}, // somewhat lax.
- {in: "foo bar=0", want: "foo bar", err: io.ErrUnexpectedEOF},
- {in: "foo bar=0D=0A", want: "foo bar\r\n"},
- {in: " A B \r\n C ", want: " A B\r\n C"},
- {in: " A B =\r\n C ", want: " A B C"},
- {in: " A B =\n C ", want: " A B C"}, // lax. treating LF as CRLF
- {in: "foo=\nbar", want: "foobar"},
- {in: "foo\x00bar", want: "foo", err: "quotedprintable: invalid unescaped byte 0x00 in body"},
- {in: "foo bar\xff", want: "foo bar", err: "quotedprintable: invalid unescaped byte 0xff in body"},
-
- // Equal sign.
- {in: "=3D30\n", want: "=30\n"},
- {in: "=00=FF0=\n", want: "\x00\xff0"},
-
- // Trailing whitespace
- {in: "foo \n", want: "foo\n"},
- {in: "foo \n\nfoo =\n\nfoo=20\n\n", want: "foo\n\nfoo \nfoo \n\n"},
-
- // Tests that we allow bare \n and \r through, despite it being strictly
- // not permitted per RFC 2045, Section 6.7 Page 22 bullet (4).
- {in: "foo\nbar", want: "foo\nbar"},
- {in: "foo\rbar", want: "foo\rbar"},
- {in: "foo\r\nbar", want: "foo\r\nbar"},
-
- // Different types of soft line-breaks.
- {in: "foo=\r\nbar", want: "foobar"},
- {in: "foo=\nbar", want: "foobar"},
- {in: "foo=\rbar", want: "foo", err: "quotedprintable: invalid hex byte 0x0d"},
- {in: "foo=\r\r\r \nbar", want: "foo", err: `quotedprintable: invalid bytes after =: "\r\r\r \n"`},
-
- // Example from RFC 2045:
- {in: "Now's the time =\n" + "for all folk to come=\n" + " to the aid of their country.",
- want: "Now's the time for all folk to come to the aid of their country."},
- }
- for _, tt := range tests {
- var buf bytes.Buffer
- _, err := io.Copy(&buf, NewReader(strings.NewReader(tt.in)))
- if got := buf.String(); got != tt.want {
- t.Errorf("for %q, got %q; want %q", tt.in, got, tt.want)
- }
- switch verr := tt.err.(type) {
- case nil:
- if err != nil {
- t.Errorf("for %q, got unexpected error: %v", tt.in, err)
- }
- case string:
- if got := fmt.Sprint(err); got != verr {
- t.Errorf("for %q, got error %q; want %q", tt.in, got, verr)
- }
- case error:
- if err != verr {
- t.Errorf("for %q, got error %q; want %q", tt.in, err, verr)
- }
- }
- }
-
-}
-
-func everySequence(base, alpha string, length int, fn func(string)) {
- if len(base) == length {
- fn(base)
- return
- }
- for i := 0; i < len(alpha); i++ {
- everySequence(base+alpha[i:i+1], alpha, length, fn)
- }
-}
-
-var useQprint = flag.Bool("qprint", false, "Compare against the 'qprint' program.")
-
-var badSoftRx = regexp.MustCompile(`=([^\r\n]+?\n)|([^\r\n]+$)|(\r$)|(\r[^\n]+\n)|( \r\n)`)
-
-func TestExhaustive(t *testing.T) {
- if *useQprint {
- _, err := exec.LookPath("qprint")
- if err != nil {
- t.Fatalf("Error looking for qprint: %v", err)
- }
- }
-
- var buf bytes.Buffer
- res := make(map[string]int)
- everySequence("", "0A \r\n=", 6, func(s string) {
- if strings.HasSuffix(s, "=") || strings.Contains(s, "==") {
- return
- }
- buf.Reset()
- _, err := io.Copy(&buf, NewReader(strings.NewReader(s)))
- if err != nil {
- errStr := err.Error()
- if strings.Contains(errStr, "invalid bytes after =:") {
- errStr = "invalid bytes after ="
- }
- res[errStr]++
- if strings.Contains(errStr, "invalid hex byte ") {
- if strings.HasSuffix(errStr, "0x20") && (strings.Contains(s, "=0 ") || strings.Contains(s, "=A ") || strings.Contains(s, "= ")) {
- return
- }
- if strings.HasSuffix(errStr, "0x3d") && (strings.Contains(s, "=0=") || strings.Contains(s, "=A=")) {
- return
- }
- if strings.HasSuffix(errStr, "0x0a") || strings.HasSuffix(errStr, "0x0d") {
- // bunch of cases; since whitespace at the end of a line before \n is removed.
- return
- }
- }
- if strings.Contains(errStr, "unexpected EOF") {
- return
- }
- if errStr == "invalid bytes after =" && badSoftRx.MatchString(s) {
- return
- }
- t.Errorf("decode(%q) = %v", s, err)
- return
- }
- if *useQprint {
- cmd := exec.Command("qprint", "-d")
- cmd.Stdin = strings.NewReader(s)
- stderr, err := cmd.StderrPipe()
- if err != nil {
- panic(err)
- }
- qpres := make(chan interface{}, 2)
- go func() {
- br := bufio.NewReader(stderr)
- s, _ := br.ReadString('\n')
- if s != "" {
- qpres <- errors.New(s)
- if cmd.Process != nil {
- // It can get stuck on invalid input, like:
- // echo -n "0000= " | qprint -d
- cmd.Process.Kill()
- }
- }
- }()
- go func() {
- want, err := cmd.Output()
- if err == nil {
- qpres <- want
- }
- }()
- select {
- case got := <-qpres:
- if want, ok := got.([]byte); ok {
- if string(want) != buf.String() {
- t.Errorf("go decode(%q) = %q; qprint = %q", s, want, buf.String())
- }
- } else {
- t.Logf("qprint -d(%q) = %v", s, got)
- }
- case <-time.After(5 * time.Second):
- t.Logf("qprint timeout on %q", s)
- }
- }
- res["OK"]++
- })
- var outcomes []string
- for k, v := range res {
- outcomes = append(outcomes, fmt.Sprintf("%v: %d", k, v))
- }
- sort.Strings(outcomes)
- got := strings.Join(outcomes, "\n")
- want := `OK: 21576
-invalid bytes after =: 3397
-quotedprintable: invalid hex byte 0x0a: 1400
-quotedprintable: invalid hex byte 0x0d: 2700
-quotedprintable: invalid hex byte 0x20: 2490
-quotedprintable: invalid hex byte 0x3d: 440
-unexpected EOF: 3122`
- if got != want {
- t.Errorf("Got:\n%s\nWant:\n%s", got, want)
- }
-}
diff --git a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/writer_test.go b/vendor/gopkg.in/alexcesaro/quotedprintable.v3/writer_test.go
deleted file mode 100644
index ed8507289..000000000
--- a/vendor/gopkg.in/alexcesaro/quotedprintable.v3/writer_test.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package quotedprintable
-
-import (
- "bytes"
- "io/ioutil"
- "strings"
- "testing"
-)
-
-func TestWriter(t *testing.T) {
- testWriter(t, false)
-}
-
-func TestWriterBinary(t *testing.T) {
- testWriter(t, true)
-}
-
-func testWriter(t *testing.T, binary bool) {
- tests := []struct {
- in, want, wantB string
- }{
- {in: "", want: ""},
- {in: "foo bar", want: "foo bar"},
- {in: "foo bar=", want: "foo bar=3D"},
- {in: "foo bar\r", want: "foo bar\r\n", wantB: "foo bar=0D"},
- {in: "foo bar\r\r", want: "foo bar\r\n\r\n", wantB: "foo bar=0D=0D"},
- {in: "foo bar\n", want: "foo bar\r\n", wantB: "foo bar=0A"},
- {in: "foo bar\r\n", want: "foo bar\r\n", wantB: "foo bar=0D=0A"},
- {in: "foo bar\r\r\n", want: "foo bar\r\n\r\n", wantB: "foo bar=0D=0D=0A"},
- {in: "foo bar ", want: "foo bar=20"},
- {in: "foo bar\t", want: "foo bar=09"},
- {in: "foo bar ", want: "foo bar =20"},
- {in: "foo bar \n", want: "foo bar=20\r\n", wantB: "foo bar =0A"},
- {in: "foo bar \r", want: "foo bar=20\r\n", wantB: "foo bar =0D"},
- {in: "foo bar \r\n", want: "foo bar=20\r\n", wantB: "foo bar =0D=0A"},
- {in: "foo bar \n", want: "foo bar =20\r\n", wantB: "foo bar =0A"},
- {in: "foo bar \n ", want: "foo bar =20\r\n=20", wantB: "foo bar =0A=20"},
- {in: "¡Hola Señor!", want: "=C2=A1Hola Se=C3=B1or!"},
- {
- in: "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~",
- want: "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~",
- },
- {
- in: strings.Repeat("a", 75),
- want: strings.Repeat("a", 75),
- },
- {
- in: strings.Repeat("a", 76),
- want: strings.Repeat("a", 75) + "=\r\na",
- },
- {
- in: strings.Repeat("a", 72) + "=",
- want: strings.Repeat("a", 72) + "=3D",
- },
- {
- in: strings.Repeat("a", 73) + "=",
- want: strings.Repeat("a", 73) + "=\r\n=3D",
- },
- {
- in: strings.Repeat("a", 74) + "=",
- want: strings.Repeat("a", 74) + "=\r\n=3D",
- },
- {
- in: strings.Repeat("a", 75) + "=",
- want: strings.Repeat("a", 75) + "=\r\n=3D",
- },
- {
- in: strings.Repeat(" ", 73),
- want: strings.Repeat(" ", 72) + "=20",
- },
- {
- in: strings.Repeat(" ", 74),
- want: strings.Repeat(" ", 73) + "=\r\n=20",
- },
- {
- in: strings.Repeat(" ", 75),
- want: strings.Repeat(" ", 74) + "=\r\n=20",
- },
- {
- in: strings.Repeat(" ", 76),
- want: strings.Repeat(" ", 75) + "=\r\n=20",
- },
- {
- in: strings.Repeat(" ", 77),
- want: strings.Repeat(" ", 75) + "=\r\n =20",
- },
- }
-
- for _, tt := range tests {
- buf := new(bytes.Buffer)
- w := NewWriter(buf)
-
- want := tt.want
- if binary {
- w.Binary = true
- if tt.wantB != "" {
- want = tt.wantB
- }
- }
-
- if _, err := w.Write([]byte(tt.in)); err != nil {
- t.Errorf("Write(%q): %v", tt.in, err)
- continue
- }
- if err := w.Close(); err != nil {
- t.Errorf("Close(): %v", err)
- continue
- }
- got := buf.String()
- if got != want {
- t.Errorf("Write(%q), got:\n%q\nwant:\n%q", tt.in, got, want)
- }
- }
-}
-
-func TestRoundTrip(t *testing.T) {
- buf := new(bytes.Buffer)
- w := NewWriter(buf)
- if _, err := w.Write(testMsg); err != nil {
- t.Fatalf("Write: %v", err)
- }
- if err := w.Close(); err != nil {
- t.Fatalf("Close: %v", err)
- }
-
- r := NewReader(buf)
- gotBytes, err := ioutil.ReadAll(r)
- if err != nil {
- t.Fatalf("Error while reading from Reader: %v", err)
- }
- got := string(gotBytes)
- if got != string(testMsg) {
- t.Errorf("Encoding and decoding changed the message, got:\n%s", got)
- }
-}
-
-// From http://fr.wikipedia.org/wiki/Quoted-Printable
-var testMsg = []byte("Quoted-Printable (QP) est un format d'encodage de données codées sur 8 bits, qui utilise exclusivement les caractères alphanumériques imprimables du code ASCII (7 bits).\r\n" +
- "\r\n" +
- "En effet, les différents codages comprennent de nombreux caractères qui ne sont pas représentables en ASCII (par exemple les caractères accentués), ainsi que des caractères dits « non-imprimables ».\r\n" +
- "\r\n" +
- "L'encodage Quoted-Printable permet de remédier à ce problème, en procédant de la manière suivante :\r\n" +
- "\r\n" +
- "Un octet correspondant à un caractère imprimable de l'ASCII sauf le signe égal (donc un caractère de code ASCII entre 33 et 60 ou entre 62 et 126) ou aux caractères de saut de ligne (codes ASCII 13 et 10) ou une suite de tabulations et espaces non situées en fin de ligne (de codes ASCII respectifs 9 et 32) est représenté tel quel.\r\n" +
- "Un octet qui ne correspond pas à la définition ci-dessus (caractère non imprimable de l'ASCII, tabulation ou espaces non suivies d'un caractère imprimable avant la fin de la ligne ou signe égal) est représenté par un signe égal, suivi de son numéro, exprimé en hexadécimal.\r\n" +
- "Enfin, un signe égal suivi par un saut de ligne (donc la suite des trois caractères de codes ASCII 61, 13 et 10) peut être inséré n'importe où, afin de limiter la taille des lignes produites si nécessaire. Une limite de 76 caractères par ligne est généralement respectée.\r\n")
-
-func BenchmarkWriter(b *testing.B) {
- for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard)
- w.Write(testMsg)
- w.Close()
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/ber_test.go b/vendor/gopkg.in/asn1-ber.v1/ber_test.go
deleted file mode 100644
index bbd22db6d..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/ber_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package ber
-
-import (
- "bytes"
- "math"
-
- "io"
- "testing"
-)
-
-func TestEncodeDecodeInteger(t *testing.T) {
- for _, v := range []int64{0, 10, 128, 1024, math.MaxInt64, -1, -100, -128, -1024, math.MinInt64} {
- enc := encodeInteger(v)
- dec, err := parseInt64(enc)
- if err != nil {
- t.Fatalf("Error decoding %d : %s", v, err)
- }
- if v != dec {
- t.Error("TestEncodeDecodeInteger failed for %d (got %d)", v, dec)
- }
-
- }
-}
-
-func TestBoolean(t *testing.T) {
- var value bool = true
-
- packet := NewBoolean(ClassUniversal, TypePrimitive, TagBoolean, value, "first Packet, True")
-
- newBoolean, ok := packet.Value.(bool)
- if !ok || newBoolean != value {
- t.Error("error during creating packet")
- }
-
- encodedPacket := packet.Bytes()
-
- newPacket := DecodePacket(encodedPacket)
-
- newBoolean, ok = newPacket.Value.(bool)
- if !ok || newBoolean != value {
- t.Error("error during decoding packet")
- }
-
-}
-
-func TestInteger(t *testing.T) {
- var value int64 = 10
-
- packet := NewInteger(ClassUniversal, TypePrimitive, TagInteger, value, "Integer, 10")
-
- {
- newInteger, ok := packet.Value.(int64)
- if !ok || newInteger != value {
- t.Error("error creating packet")
- }
- }
-
- encodedPacket := packet.Bytes()
-
- newPacket := DecodePacket(encodedPacket)
-
- {
- newInteger, ok := newPacket.Value.(int64)
- if !ok || int64(newInteger) != value {
- t.Error("error decoding packet")
- }
- }
-}
-
-func TestString(t *testing.T) {
- var value string = "Hic sunt dracones"
-
- packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, value, "String")
-
- newValue, ok := packet.Value.(string)
- if !ok || newValue != value {
- t.Error("error during creating packet")
- }
-
- encodedPacket := packet.Bytes()
-
- newPacket := DecodePacket(encodedPacket)
-
- newValue, ok = newPacket.Value.(string)
- if !ok || newValue != value {
- t.Error("error during decoding packet")
- }
-
-}
-
-func TestSequenceAndAppendChild(t *testing.T) {
-
- values := []string{
- "HIC SVNT LEONES",
- "Iñtërnâtiônàlizætiøn",
- "Terra Incognita",
- }
-
- sequence := NewSequence("a sequence")
- for _, s := range values {
- sequence.AppendChild(NewString(ClassUniversal, TypePrimitive, TagOctetString, s, "String"))
- }
-
- if len(sequence.Children) != len(values) {
- t.Errorf("wrong length for children array should be %d, got %d", len(values), len(sequence.Children))
- }
-
- encodedSequence := sequence.Bytes()
-
- decodedSequence := DecodePacket(encodedSequence)
- if len(decodedSequence.Children) != len(values) {
- t.Errorf("wrong length for children array should be %d => %d", len(values), len(decodedSequence.Children))
- }
-
- for i, s := range values {
- if decodedSequence.Children[i].Value.(string) != s {
- t.Errorf("expected %d to be %q, got %q", i, s, decodedSequence.Children[i].Value.(string))
- }
- }
-}
-
-func TestReadPacket(t *testing.T) {
- packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, "Ad impossibilia nemo tenetur", "string")
- var buffer io.ReadWriter
- buffer = new(bytes.Buffer)
-
- buffer.Write(packet.Bytes())
-
- newPacket, err := ReadPacket(buffer)
- if err != nil {
- t.Error("error during ReadPacket", err)
- }
- newPacket.ByteValue = nil
- if !bytes.Equal(newPacket.ByteValue, packet.ByteValue) {
- t.Error("packets should be the same")
- }
-}
-
-func TestBinaryInteger(t *testing.T) {
- // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.7
- var data = []struct {
- v int64
- e []byte
- }{
- {v: 0, e: []byte{0x02, 0x01, 0x00}},
- {v: 127, e: []byte{0x02, 0x01, 0x7F}},
- {v: 128, e: []byte{0x02, 0x02, 0x00, 0x80}},
- {v: 256, e: []byte{0x02, 0x02, 0x01, 0x00}},
- {v: -128, e: []byte{0x02, 0x01, 0x80}},
- {v: -129, e: []byte{0x02, 0x02, 0xFF, 0x7F}},
- {v: math.MaxInt64, e: []byte{0x02, 0x08, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
- {v: math.MinInt64, e: []byte{0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
- }
-
- for _, d := range data {
- if b := NewInteger(ClassUniversal, TypePrimitive, TagInteger, int64(d.v), "").Bytes(); !bytes.Equal(d.e, b) {
- t.Errorf("Wrong binary generated for %d : got % X, expected % X", d.v, b, d.e)
- }
- }
-}
-
-func TestBinaryOctetString(t *testing.T) {
- // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.10
-
- if !bytes.Equal([]byte{0x04, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, NewString(ClassUniversal, TypePrimitive, TagOctetString, "\x01\x23\x45\x67\x89\xab\xcd\xef", "").Bytes()) {
- t.Error("wrong binary generated")
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/header_test.go b/vendor/gopkg.in/asn1-ber.v1/header_test.go
deleted file mode 100644
index cac1e2e2b..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/header_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package ber
-
-import (
- "bytes"
- "io"
- "testing"
-)
-
-func TestReadHeader(t *testing.T) {
- testcases := map[string]struct {
- Data []byte
- ExpectedIdentifier Identifier
- ExpectedLength int
- ExpectedBytesRead int
- ExpectedError string
- }{
- "empty": {
- Data: []byte{},
- ExpectedIdentifier: Identifier{},
- ExpectedLength: 0,
- ExpectedBytesRead: 0,
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- },
-
- "valid short form": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypePrimitive) | byte(TagCharacterString),
- 127,
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagCharacterString,
- },
- ExpectedLength: 127,
- ExpectedBytesRead: 2,
- ExpectedError: "",
- },
-
- "valid long form": {
- Data: []byte{
- // 2-byte encoding of tag
- byte(ClassUniversal) | byte(TypePrimitive) | byte(HighTag),
- byte(TagCharacterString),
-
- // 2-byte encoding of length
- LengthLongFormBitmask | 1,
- 127,
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagCharacterString,
- },
- ExpectedLength: 127,
- ExpectedBytesRead: 4,
- ExpectedError: "",
- },
-
- "valid indefinite length": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(TagCharacterString),
- LengthLongFormBitmask,
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagCharacterString,
- },
- ExpectedLength: LengthIndefinite,
- ExpectedBytesRead: 2,
- ExpectedError: "",
- },
-
- "invalid indefinite length": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypePrimitive) | byte(TagCharacterString),
- LengthLongFormBitmask,
- },
- ExpectedIdentifier: Identifier{},
- ExpectedLength: 0,
- ExpectedBytesRead: 2,
- ExpectedError: "indefinite length used with primitive type",
- },
- }
-
- for k, tc := range testcases {
- reader := bytes.NewBuffer(tc.Data)
- identifier, length, read, err := readHeader(reader)
-
- if err != nil {
- if tc.ExpectedError == "" {
- t.Errorf("%s: unexpected error: %v", k, err)
- } else if err.Error() != tc.ExpectedError {
- t.Errorf("%s: expected error %v, got %v", k, tc.ExpectedError, err)
- }
- } else if tc.ExpectedError != "" {
- t.Errorf("%s: expected error %v, got none", k, tc.ExpectedError)
- continue
- }
-
- if read != tc.ExpectedBytesRead {
- t.Errorf("%s: expected read %d, got %d", k, tc.ExpectedBytesRead, read)
- }
-
- if identifier.ClassType != tc.ExpectedIdentifier.ClassType {
- t.Errorf("%s: expected class type %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.ClassType,
- ClassMap[tc.ExpectedIdentifier.ClassType],
- identifier.ClassType,
- ClassMap[identifier.ClassType],
- )
- }
- if identifier.TagType != tc.ExpectedIdentifier.TagType {
- t.Errorf("%s: expected tag type %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.TagType,
- TypeMap[tc.ExpectedIdentifier.TagType],
- identifier.TagType,
- TypeMap[identifier.TagType],
- )
- }
- if identifier.Tag != tc.ExpectedIdentifier.Tag {
- t.Errorf("%s: expected tag %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.Tag,
- tagMap[tc.ExpectedIdentifier.Tag],
- identifier.Tag,
- tagMap[identifier.Tag],
- )
- }
-
- if length != tc.ExpectedLength {
- t.Errorf("%s: expected length %d, got %d", k, tc.ExpectedLength, length)
- }
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/identifier_test.go b/vendor/gopkg.in/asn1-ber.v1/identifier_test.go
deleted file mode 100644
index 7169362e2..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/identifier_test.go
+++ /dev/null
@@ -1,344 +0,0 @@
-package ber
-
-import (
- "bytes"
- "io"
- "math"
- "testing"
-)
-
-func TestReadIdentifier(t *testing.T) {
- testcases := map[string]struct {
- Data []byte
-
- ExpectedIdentifier Identifier
- ExpectedBytesRead int
- ExpectedError string
- }{
- "empty": {
- Data: []byte{},
- ExpectedBytesRead: 0,
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- },
-
- "universal primitive eoc": {
- Data: []byte{byte(ClassUniversal) | byte(TypePrimitive) | byte(TagEOC)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagEOC,
- },
- ExpectedBytesRead: 1,
- },
- "universal primitive character string": {
- Data: []byte{byte(ClassUniversal) | byte(TypePrimitive) | byte(TagCharacterString)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagCharacterString,
- },
- ExpectedBytesRead: 1,
- },
-
- "universal constructed bit string": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(TagBitString)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagBitString,
- },
- ExpectedBytesRead: 1,
- },
- "universal constructed character string": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(TagCharacterString)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagCharacterString,
- },
- ExpectedBytesRead: 1,
- },
-
- "application constructed object descriptor": {
- Data: []byte{byte(ClassApplication) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassApplication,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytesRead: 1,
- },
- "context constructed object descriptor": {
- Data: []byte{byte(ClassContext) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassContext,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytesRead: 1,
- },
- "private constructed object descriptor": {
- Data: []byte{byte(ClassPrivate) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- ExpectedIdentifier: Identifier{
- ClassType: ClassPrivate,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytesRead: 1,
- },
-
- "high-tag-number tag missing bytes": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag)},
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- ExpectedBytesRead: 1,
- },
- "high-tag-number tag invalid first byte": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag), 0x0},
- ExpectedError: "invalid first high-tag-number tag byte",
- ExpectedBytesRead: 2,
- },
- "high-tag-number tag invalid first byte with continue bit": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag), byte(HighTagContinueBitmask)},
- ExpectedError: "invalid first high-tag-number tag byte",
- ExpectedBytesRead: 2,
- },
- "high-tag-number tag continuation missing bytes": {
- Data: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag), byte(HighTagContinueBitmask | 0x1)},
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- ExpectedBytesRead: 2,
- },
- "high-tag-number tag overflow": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(HighTagContinueBitmask | 0x1),
- byte(0x1),
- },
- ExpectedError: "high-tag-number tag overflow",
- ExpectedBytesRead: 11,
- },
- "max high-tag-number tag": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(0x7f),
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: Tag(0x7FFFFFFFFFFFFFFF), // 01111111...(63)...11111b
- },
- ExpectedBytesRead: 10,
- },
- "high-tag-number encoding of low-tag value": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(TagObjectDescriptor),
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytesRead: 2,
- },
- "max high-tag-number tag ignores extra data": {
- Data: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(0x7f),
- byte(0x01), // extra data, shouldn't be read
- byte(0x02), // extra data, shouldn't be read
- byte(0x03), // extra data, shouldn't be read
- },
- ExpectedIdentifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: Tag(0x7FFFFFFFFFFFFFFF), // 01111111...(63)...11111b
- },
- ExpectedBytesRead: 10,
- },
- }
-
- for k, tc := range testcases {
- reader := bytes.NewBuffer(tc.Data)
- identifier, read, err := readIdentifier(reader)
-
- if err != nil {
- if tc.ExpectedError == "" {
- t.Errorf("%s: unexpected error: %v", k, err)
- } else if err.Error() != tc.ExpectedError {
- t.Errorf("%s: expected error %v, got %v", k, tc.ExpectedError, err)
- }
- } else if tc.ExpectedError != "" {
- t.Errorf("%s: expected error %v, got none", k, tc.ExpectedError)
- continue
- }
-
- if read != tc.ExpectedBytesRead {
- t.Errorf("%s: expected read %d, got %d", k, tc.ExpectedBytesRead, read)
- }
-
- if identifier.ClassType != tc.ExpectedIdentifier.ClassType {
- t.Errorf("%s: expected class type %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.ClassType,
- ClassMap[tc.ExpectedIdentifier.ClassType],
- identifier.ClassType,
- ClassMap[identifier.ClassType],
- )
- }
- if identifier.TagType != tc.ExpectedIdentifier.TagType {
- t.Errorf("%s: expected tag type %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.TagType,
- TypeMap[tc.ExpectedIdentifier.TagType],
- identifier.TagType,
- TypeMap[identifier.TagType],
- )
- }
- if identifier.Tag != tc.ExpectedIdentifier.Tag {
- t.Errorf("%s: expected tag %d (%s), got %d (%s)", k,
- tc.ExpectedIdentifier.Tag,
- tagMap[tc.ExpectedIdentifier.Tag],
- identifier.Tag,
- tagMap[identifier.Tag],
- )
- }
- }
-}
-
-func TestEncodeIdentifier(t *testing.T) {
- testcases := map[string]struct {
- Identifier Identifier
- ExpectedBytes []byte
- }{
- "universal primitive eoc": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagEOC,
- },
- ExpectedBytes: []byte{byte(ClassUniversal) | byte(TypePrimitive) | byte(TagEOC)},
- },
- "universal primitive character string": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypePrimitive,
- Tag: TagCharacterString,
- },
- ExpectedBytes: []byte{byte(ClassUniversal) | byte(TypePrimitive) | byte(TagCharacterString)},
- },
-
- "universal constructed bit string": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagBitString,
- },
- ExpectedBytes: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(TagBitString)},
- },
- "universal constructed character string": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagCharacterString,
- },
- ExpectedBytes: []byte{byte(ClassUniversal) | byte(TypeConstructed) | byte(TagCharacterString)},
- },
-
- "application constructed object descriptor": {
- Identifier: Identifier{
- ClassType: ClassApplication,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytes: []byte{byte(ClassApplication) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- },
- "context constructed object descriptor": {
- Identifier: Identifier{
- ClassType: ClassContext,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytes: []byte{byte(ClassContext) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- },
- "private constructed object descriptor": {
- Identifier: Identifier{
- ClassType: ClassPrivate,
- TagType: TypeConstructed,
- Tag: TagObjectDescriptor,
- },
- ExpectedBytes: []byte{byte(ClassPrivate) | byte(TypeConstructed) | byte(TagObjectDescriptor)},
- },
-
- "max low-tag-number tag": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagBMPString,
- },
- ExpectedBytes: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(TagBMPString),
- },
- },
-
- "min high-tag-number tag": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: TagBMPString + 1,
- },
- ExpectedBytes: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(TagBMPString + 1),
- },
- },
-
- "max high-tag-number tag": {
- Identifier: Identifier{
- ClassType: ClassUniversal,
- TagType: TypeConstructed,
- Tag: Tag(math.MaxInt64),
- },
- ExpectedBytes: []byte{
- byte(ClassUniversal) | byte(TypeConstructed) | byte(HighTag),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(HighTagContinueBitmask | 0x7f),
- byte(0x7f),
- },
- },
- }
-
- for k, tc := range testcases {
- b := encodeIdentifier(tc.Identifier)
- if bytes.Compare(tc.ExpectedBytes, b) != 0 {
- t.Errorf("%s: Expected\n\t%#v\ngot\n\t%#v", k, tc.ExpectedBytes, b)
- }
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/length_test.go b/vendor/gopkg.in/asn1-ber.v1/length_test.go
deleted file mode 100644
index 289510a8d..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/length_test.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package ber
-
-import (
- "bytes"
- "io"
- "math"
- "testing"
-)
-
-func TestReadLength(t *testing.T) {
- testcases := map[string]struct {
- Data []byte
-
- ExpectedLength int64
- ExpectedBytesRead int
- ExpectedError string
- }{
- "empty": {
- Data: []byte{},
- ExpectedBytesRead: 0,
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- },
- "invalid first byte": {
- Data: []byte{0xFF},
- ExpectedBytesRead: 1,
- ExpectedError: "invalid length byte 0xff",
- },
-
- "indefinite form": {
- Data: []byte{LengthLongFormBitmask},
- ExpectedLength: LengthIndefinite,
- ExpectedBytesRead: 1,
- },
-
- "short-definite-form zero length": {
- Data: []byte{0},
- ExpectedLength: 0,
- ExpectedBytesRead: 1,
- },
- "short-definite-form length 1": {
- Data: []byte{1},
- ExpectedLength: 1,
- ExpectedBytesRead: 1,
- },
- "short-definite-form max length": {
- Data: []byte{127},
- ExpectedLength: 127,
- ExpectedBytesRead: 1,
- },
-
- "long-definite-form missing bytes": {
- Data: []byte{LengthLongFormBitmask | 1},
- ExpectedBytesRead: 1,
- ExpectedError: io.ErrUnexpectedEOF.Error(),
- },
- "long-definite-form overflow": {
- Data: []byte{LengthLongFormBitmask | 9},
- ExpectedBytesRead: 1,
- ExpectedError: "long-form length overflow",
- },
- "long-definite-form zero length": {
- Data: []byte{LengthLongFormBitmask | 1, 0x0},
- ExpectedLength: 0,
- ExpectedBytesRead: 2,
- },
- "long-definite-form length 127": {
- Data: []byte{LengthLongFormBitmask | 1, 127},
- ExpectedLength: 127,
- ExpectedBytesRead: 2,
- },
- "long-definite-form max length (32-bit)": {
- Data: []byte{
- LengthLongFormBitmask | 4,
- 0x7F,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- },
- ExpectedLength: math.MaxInt32,
- ExpectedBytesRead: 5,
- },
- "long-definite-form max length (64-bit)": {
- Data: []byte{
- LengthLongFormBitmask | 8,
- 0x7F,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- },
- ExpectedLength: math.MaxInt64,
- ExpectedBytesRead: 9,
- },
- }
-
- for k, tc := range testcases {
- // Skip tests requiring 64-bit integers on platforms that don't support them
- if tc.ExpectedLength != int64(int(tc.ExpectedLength)) {
- continue
- }
-
- reader := bytes.NewBuffer(tc.Data)
- length, read, err := readLength(reader)
-
- if err != nil {
- if tc.ExpectedError == "" {
- t.Errorf("%s: unexpected error: %v", k, err)
- } else if err.Error() != tc.ExpectedError {
- t.Errorf("%s: expected error %v, got %v", k, tc.ExpectedError, err)
- }
- } else if tc.ExpectedError != "" {
- t.Errorf("%s: expected error %v, got none", k, tc.ExpectedError)
- continue
- }
-
- if read != tc.ExpectedBytesRead {
- t.Errorf("%s: expected read %d, got %d", k, tc.ExpectedBytesRead, read)
- }
-
- if int64(length) != tc.ExpectedLength {
- t.Errorf("%s: expected length %d, got %d", k, tc.ExpectedLength, length)
- }
- }
-}
-
-func TestEncodeLength(t *testing.T) {
- testcases := map[string]struct {
- Length int64
- ExpectedBytes []byte
- }{
- "0": {
- Length: 0,
- ExpectedBytes: []byte{0},
- },
- "1": {
- Length: 1,
- ExpectedBytes: []byte{1},
- },
-
- "max short-form length": {
- Length: 127,
- ExpectedBytes: []byte{127},
- },
- "min long-form length": {
- Length: 128,
- ExpectedBytes: []byte{LengthLongFormBitmask | 1, 128},
- },
-
- "max long-form length (32-bit)": {
- Length: math.MaxInt32,
- ExpectedBytes: []byte{
- LengthLongFormBitmask | 4,
- 0x7F,
- 0xFF,
- 0xFF,
- 0xFF,
- },
- },
-
- "max long-form length (64-bit)": {
- Length: math.MaxInt64,
- ExpectedBytes: []byte{
- LengthLongFormBitmask | 8,
- 0x7F,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- 0xFF,
- },
- },
- }
-
- for k, tc := range testcases {
- // Skip tests requiring 64-bit integers on platforms that don't support them
- if tc.Length != int64(int(tc.Length)) {
- continue
- }
-
- b := encodeLength(int(tc.Length))
- if bytes.Compare(tc.ExpectedBytes, b) != 0 {
- t.Errorf("%s: Expected\n\t%#v\ngot\n\t%#v", k, tc.ExpectedBytes, b)
- }
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/suite_test.go b/vendor/gopkg.in/asn1-ber.v1/suite_test.go
deleted file mode 100644
index ace8e6705..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/suite_test.go
+++ /dev/null
@@ -1,182 +0,0 @@
-package ber
-
-import (
- "bytes"
- "io"
- "io/ioutil"
- "testing"
-)
-
-var errEOF = io.ErrUnexpectedEOF.Error()
-
-// Tests from http://www.strozhevsky.com/free_docs/free_asn1_testsuite_descr.pdf
-// Source files and descriptions at http://www.strozhevsky.com/free_docs/TEST_SUITE.zip
-var testcases = []struct {
- // File contains the path to the BER-encoded file
- File string
- // Error indicates whether a decoding error is expected
- Error string
- // AbnormalEncoding indicates whether a normalized re-encoding is expected to differ from the original source
- AbnormalEncoding bool
- // IndefiniteEncoding indicates the source file used indefinite-length encoding, so the re-encoding is expected to differ (since the length is known)
- IndefiniteEncoding bool
-}{
- // Common blocks
- {File: "tests/tc1.ber", Error: "high-tag-number tag overflow"},
- {File: "tests/tc2.ber", Error: errEOF},
- {File: "tests/tc3.ber", Error: errEOF},
- {File: "tests/tc4.ber", Error: "invalid length byte 0xff"},
- {File: "tests/tc5.ber", Error: "", AbnormalEncoding: true},
- // Real numbers (some expected failures are disabled until support is added)
- {File: "tests/tc6.ber", Error: ""}, // Error: "REAL value +0 must be encoded with zero-length value block"},
- {File: "tests/tc7.ber", Error: ""}, // Error: "REAL value -0 must be encoded as a special value"},
- {File: "tests/tc8.ber", Error: ""},
- {File: "tests/tc9.ber", Error: ""}, // Error: "Bits 6 and 5 of information octet for REAL are equal to 11"
- {File: "tests/tc10.ber", Error: ""},
- {File: "tests/tc11.ber", Error: ""}, // Error: "Incorrect NR form"
- {File: "tests/tc12.ber", Error: ""}, // Error: "Encoding of "special value" not from ASN.1 standard"
- {File: "tests/tc13.ber", Error: errEOF},
- {File: "tests/tc14.ber", Error: errEOF},
- {File: "tests/tc15.ber", Error: ""}, // Error: "Too big value of exponent"
- {File: "tests/tc16.ber", Error: ""}, // Error: "Too big value of mantissa"
- {File: "tests/tc17.ber", Error: ""}, // Error: "Too big values for exponent and mantissa + using of "scaling factor" value"
- // Integers
- {File: "tests/tc18.ber", Error: ""},
- {File: "tests/tc19.ber", Error: errEOF},
- {File: "tests/tc20.ber", Error: ""},
- // Object identifiers
- {File: "tests/tc21.ber", Error: ""},
- {File: "tests/tc22.ber", Error: ""},
- {File: "tests/tc23.ber", Error: errEOF},
- {File: "tests/tc24.ber", Error: ""},
- // Booleans
- {File: "tests/tc25.ber", Error: ""},
- {File: "tests/tc26.ber", Error: ""},
- {File: "tests/tc27.ber", Error: errEOF},
- {File: "tests/tc28.ber", Error: ""},
- {File: "tests/tc29.ber", Error: ""},
- // Null
- {File: "tests/tc30.ber", Error: ""},
- {File: "tests/tc31.ber", Error: errEOF},
- {File: "tests/tc32.ber", Error: ""},
- // Bitstring (some expected failures are disabled until support is added)
- {File: "tests/tc33.ber", Error: ""}, // Error: "Too big value for "unused bits""
- {File: "tests/tc34.ber", Error: errEOF},
- {File: "tests/tc35.ber", Error: "", IndefiniteEncoding: true}, // Error: "Using of different from BIT STRING types as internal types for constructive encoding"
- {File: "tests/tc36.ber", Error: "", IndefiniteEncoding: true}, // Error: "Using of "unused bits" in internal BIT STRINGs with constructive form of encoding"
- {File: "tests/tc37.ber", Error: ""},
- {File: "tests/tc38.ber", Error: "", IndefiniteEncoding: true},
- {File: "tests/tc39.ber", Error: ""},
- {File: "tests/tc40.ber", Error: ""},
- // Octet string (some expected failures are disabled until support is added)
- {File: "tests/tc41.ber", Error: "", IndefiniteEncoding: true}, // Error: "Using of different from OCTET STRING types as internal types for constructive encoding"
- {File: "tests/tc42.ber", Error: errEOF},
- {File: "tests/tc43.ber", Error: errEOF},
- {File: "tests/tc44.ber", Error: ""},
- {File: "tests/tc45.ber", Error: ""},
- // Bitstring
- {File: "tests/tc46.ber", Error: "indefinite length used with primitive type"},
- {File: "tests/tc47.ber", Error: "eoc child not allowed with definite length"},
- {File: "tests/tc48.ber", Error: "", IndefiniteEncoding: true}, // Error: "Using of more than 7 "unused bits" in BIT STRING with constrictive encoding form"
-}
-
-func TestSuiteDecodePacket(t *testing.T) {
- // Debug = true
- for _, tc := range testcases {
- file := tc.File
-
- dataIn, err := ioutil.ReadFile(file)
- if err != nil {
- t.Errorf("%s: %v", file, err)
- continue
- }
-
- // fmt.Printf("%s: decode %d\n", file, len(dataIn))
- packet, err := DecodePacketErr(dataIn)
- if err != nil {
- if tc.Error == "" {
- t.Errorf("%s: unexpected error during DecodePacket: %v", file, err)
- } else if tc.Error != err.Error() {
- t.Errorf("%s: expected error %q during DecodePacket, got %q", file, tc.Error, err)
- }
- continue
- }
- if tc.Error != "" {
- t.Errorf("%s: expected error %q, got none", file, tc.Error)
- continue
- }
-
- dataOut := packet.Bytes()
- if tc.AbnormalEncoding || tc.IndefiniteEncoding {
- // Abnormal encodings and encodings that used indefinite length should re-encode differently
- if bytes.Equal(dataOut, dataIn) {
- t.Errorf("%s: data should have been re-encoded differently", file)
- }
- } else if !bytes.Equal(dataOut, dataIn) {
- // Make sure the serialized data matches the source
- t.Errorf("%s: data should be the same", file)
- }
-
- packet, err = DecodePacketErr(dataOut)
- if err != nil {
- t.Errorf("%s: unexpected error: %v", file, err)
- continue
- }
-
- // Make sure the re-serialized data matches our original serialization
- dataOut2 := packet.Bytes()
- if !bytes.Equal(dataOut, dataOut2) {
- t.Errorf("%s: data should be the same", file)
- }
- }
-}
-
-func TestSuiteReadPacket(t *testing.T) {
- for _, tc := range testcases {
- file := tc.File
-
- dataIn, err := ioutil.ReadFile(file)
- if err != nil {
- t.Errorf("%s: %v", file, err)
- continue
- }
-
- buffer := bytes.NewBuffer(dataIn)
- packet, err := ReadPacket(buffer)
- if err != nil {
- if tc.Error == "" {
- t.Errorf("%s: unexpected error during ReadPacket: %v", file, err)
- } else if tc.Error != err.Error() {
- t.Errorf("%s: expected error %q during ReadPacket, got %q", file, tc.Error, err)
- }
- continue
- }
- if tc.Error != "" {
- t.Errorf("%s: expected error %q, got none", file, tc.Error)
- continue
- }
-
- dataOut := packet.Bytes()
- if tc.AbnormalEncoding || tc.IndefiniteEncoding {
- // Abnormal encodings and encodings that used indefinite length should re-encode differently
- if bytes.Equal(dataOut, dataIn) {
- t.Errorf("%s: data should have been re-encoded differently", file)
- }
- } else if !bytes.Equal(dataOut, dataIn) {
- // Make sure the serialized data matches the source
- t.Errorf("%s: data should be the same", file)
- }
-
- packet, err = DecodePacketErr(dataOut)
- if err != nil {
- t.Errorf("%s: unexpected error: %v", file, err)
- continue
- }
-
- // Make sure the re-serialized data matches our original serialization
- dataOut2 := packet.Bytes()
- if !bytes.Equal(dataOut, dataOut2) {
- t.Errorf("%s: data should be the same", file)
- }
- }
-}
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc1.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc1.ber
deleted file mode 100644
index 5c6ba1c6a..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc1.ber
+++ /dev/null
@@ -1 +0,0 @@
-@ \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc10.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc10.ber
deleted file mode 100644
index f733125d4..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc10.ber
+++ /dev/null
@@ -1 +0,0 @@
-  \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc11.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc11.ber
deleted file mode 100644
index cc4a609c8..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc11.ber
+++ /dev/null
@@ -1 +0,0 @@
-  015625 \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc12.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc12.ber
deleted file mode 100644
index dbb538d69..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc12.ber
+++ /dev/null
@@ -1 +0,0 @@
- I \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc13.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc13.ber
deleted file mode 100644
index f4f438e0d..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc13.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc14.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc14.ber
deleted file mode 100644
index b6f2fd3a4..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc14.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc15.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc15.ber
deleted file mode 100644
index 3d6da6764..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc15.ber
+++ /dev/null
@@ -1 +0,0 @@
-  \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc16.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc16.ber
deleted file mode 100644
index 68634f5f3..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc16.ber
+++ /dev/null
@@ -1 +0,0 @@
-  \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc17.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc17.ber
deleted file mode 100644
index adb9e3320..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc17.ber
+++ /dev/null
@@ -1 +0,0 @@
-   \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc18.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc18.ber
deleted file mode 100644
index fb6843f7f..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc18.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc19.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc19.ber
deleted file mode 100644
index 03afaa5de..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc19.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc2.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc2.ber
deleted file mode 100644
index 7e785773c..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc2.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc20.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc20.ber
deleted file mode 100644
index a976464b9..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc20.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc21.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc21.ber
deleted file mode 100644
index d6c2f9aa7..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc21.ber
+++ /dev/null
@@ -1 +0,0 @@
-Q \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc22.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc22.ber
deleted file mode 100644
index d1d70afab..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc22.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc23.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc23.ber
deleted file mode 100644
index 0e8d18f62..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc23.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc24.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc24.ber
deleted file mode 100644
index 10565aefa..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc24.ber
+++ /dev/null
@@ -1 +0,0 @@
-`HO Jc/ \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc25.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc25.ber
deleted file mode 100644
index 1e1140524..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc25.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc26.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc26.ber
deleted file mode 100644
index d28653b3b..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc26.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc27.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc27.ber
deleted file mode 100644
index c8c781144..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc27.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc28.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc28.ber
deleted file mode 100644
index 415fe23ed..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc28.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc29.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc29.ber
deleted file mode 100644
index 4076f4487..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc29.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc3.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc3.ber
deleted file mode 100644
index c05c900b6..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc3.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc30.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc30.ber
deleted file mode 100644
index 72bcf80f4..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc30.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc31.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc31.ber
deleted file mode 100644
index 1fcc4f254..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc31.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc32.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc32.ber
deleted file mode 100644
index 19b3e940a..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc32.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc33.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc33.ber
deleted file mode 100644
index 6ea70c4d2..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc33.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc34.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc34.ber
deleted file mode 100644
index 61337095d..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc34.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc35.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc35.ber
deleted file mode 100644
index d27eb301a..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc35.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc36.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc36.ber
deleted file mode 100644
index e5baaeacd..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc36.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc37.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc37.ber
deleted file mode 100644
index d0b1cfbe1..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc37.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc38.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc38.ber
deleted file mode 100644
index 090bce74b..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc38.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc39.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc39.ber
deleted file mode 100644
index d9d01199b..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc39.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc4.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc4.ber
deleted file mode 100644
index 2b888baac..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc4.ber
+++ /dev/null
@@ -1 +0,0 @@
- \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc40.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc40.ber
deleted file mode 100644
index 15294a501..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc40.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc41.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc41.ber
deleted file mode 100644
index 276836b65..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc41.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc42.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc42.ber
deleted file mode 100644
index 21cbfd10f..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc42.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc43.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc43.ber
deleted file mode 100644
index 98dbd7419..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc43.ber
+++ /dev/null
@@ -1 +0,0 @@
-$ \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc44.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc44.ber
deleted file mode 100644
index d825e1ad7..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc44.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc45.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc45.ber
deleted file mode 100644
index 7b861b02c..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc45.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc46.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc46.ber
deleted file mode 100644
index e78deee34..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc46.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc47.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc47.ber
deleted file mode 100644
index 190bb86f6..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc47.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc48.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc48.ber
deleted file mode 100644
index f7f111ae6..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc48.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc5.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc5.ber
deleted file mode 100644
index 45e0a0093..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc5.ber
+++ /dev/null
@@ -1 +0,0 @@
-@ \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc6.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc6.ber
deleted file mode 100644
index cee1aaf0c..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc6.ber
+++ /dev/null
@@ -1 +0,0 @@
- +0.E-5 \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc7.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc7.ber
deleted file mode 100644
index d5ae68572..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc7.ber
+++ /dev/null
@@ -1 +0,0 @@
- -0.E-5 \ No newline at end of file
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc8.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc8.ber
deleted file mode 100644
index cb32a09cb..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc8.ber
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/asn1-ber.v1/tests/tc9.ber b/vendor/gopkg.in/asn1-ber.v1/tests/tc9.ber
deleted file mode 100644
index 50b43a510..000000000
--- a/vendor/gopkg.in/asn1-ber.v1/tests/tc9.ber
+++ /dev/null
@@ -1 +0,0 @@
-  \ No newline at end of file
diff --git a/vendor/gopkg.in/gomail.v2/auth_test.go b/vendor/gopkg.in/gomail.v2/auth_test.go
deleted file mode 100644
index 20b477214..000000000
--- a/vendor/gopkg.in/gomail.v2/auth_test.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package gomail
-
-import (
- "net/smtp"
- "testing"
-)
-
-const (
- testUser = "user"
- testPwd = "pwd"
- testHost = "smtp.example.com"
-)
-
-var testAuth = &plainAuth{
- username: testUser,
- password: testPwd,
- host: testHost,
-}
-
-type plainAuthTest struct {
- auths []string
- challenges []string
- tls bool
- wantProto string
- wantData []string
- wantError bool
-}
-
-func TestNoAdvertisement(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{},
- challenges: []string{"Username:", "Password:"},
- tls: false,
- wantProto: "PLAIN",
- wantError: true,
- })
-}
-
-func TestNoAdvertisementTLS(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{},
- challenges: []string{"Username:", "Password:"},
- tls: true,
- wantProto: "PLAIN",
- wantData: []string{"\x00" + testUser + "\x00" + testPwd},
- })
-}
-
-func TestPlain(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"PLAIN"},
- challenges: []string{"Username:", "Password:"},
- tls: false,
- wantProto: "PLAIN",
- wantData: []string{"\x00" + testUser + "\x00" + testPwd},
- })
-}
-
-func TestPlainTLS(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"PLAIN"},
- challenges: []string{"Username:", "Password:"},
- tls: true,
- wantProto: "PLAIN",
- wantData: []string{"\x00" + testUser + "\x00" + testPwd},
- })
-}
-
-func TestPlainAndLogin(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"PLAIN", "LOGIN"},
- challenges: []string{"Username:", "Password:"},
- tls: false,
- wantProto: "PLAIN",
- wantData: []string{"\x00" + testUser + "\x00" + testPwd},
- })
-}
-
-func TestPlainAndLoginTLS(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"PLAIN", "LOGIN"},
- challenges: []string{"Username:", "Password:"},
- tls: true,
- wantProto: "PLAIN",
- wantData: []string{"\x00" + testUser + "\x00" + testPwd},
- })
-}
-
-func TestLogin(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"LOGIN"},
- challenges: []string{"Username:", "Password:"},
- tls: false,
- wantProto: "LOGIN",
- wantData: []string{"", testUser, testPwd},
- })
-}
-
-func TestLoginTLS(t *testing.T) {
- testPlainAuth(t, &plainAuthTest{
- auths: []string{"LOGIN"},
- challenges: []string{"Username:", "Password:"},
- tls: true,
- wantProto: "LOGIN",
- wantData: []string{"", testUser, testPwd},
- })
-}
-
-func testPlainAuth(t *testing.T, test *plainAuthTest) {
- auth := &plainAuth{
- username: testUser,
- password: testPwd,
- host: testHost,
- }
- server := &smtp.ServerInfo{
- Name: testHost,
- TLS: test.tls,
- Auth: test.auths,
- }
- proto, toServer, err := auth.Start(server)
- if err != nil && !test.wantError {
- t.Fatalf("plainAuth.Start(): %v", err)
- }
- if err != nil && test.wantError {
- return
- }
- if proto != test.wantProto {
- t.Errorf("invalid protocol, got %q, want %q", proto, test.wantProto)
- }
-
- i := 0
- got := string(toServer)
- if got != test.wantData[i] {
- t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
- }
-
- if proto == "PLAIN" {
- return
- }
-
- for _, challenge := range test.challenges {
- i++
- if i >= len(test.wantData) {
- t.Fatalf("unexpected challenge: %q", challenge)
- }
-
- toServer, err = auth.Next([]byte(challenge), true)
- if err != nil {
- t.Fatalf("plainAuth.Auth(): %v", err)
- }
- got = string(toServer)
- if got != test.wantData[i] {
- t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
- }
- }
-}
diff --git a/vendor/gopkg.in/gomail.v2/example_test.go b/vendor/gopkg.in/gomail.v2/example_test.go
deleted file mode 100644
index 8d9c6c293..000000000
--- a/vendor/gopkg.in/gomail.v2/example_test.go
+++ /dev/null
@@ -1,215 +0,0 @@
-package gomail_test
-
-import (
- "fmt"
- "html/template"
- "io"
- "log"
- "time"
-
- "gopkg.in/gomail.v2"
-)
-
-func Example() {
- m := gomail.NewMessage()
- m.SetHeader("From", "alex@example.com")
- m.SetHeader("To", "bob@example.com", "cora@example.com")
- m.SetAddressHeader("Cc", "dan@example.com", "Dan")
- m.SetHeader("Subject", "Hello!")
- m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
- m.Attach("/home/Alex/lolcat.jpg")
-
- d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
-
- // Send the email to Bob, Cora and Dan.
- if err := d.DialAndSend(m); err != nil {
- panic(err)
- }
-}
-
-// A daemon that listens to a channel and sends all incoming messages.
-func Example_daemon() {
- ch := make(chan *gomail.Message)
-
- go func() {
- d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
-
- var s gomail.SendCloser
- var err error
- open := false
- for {
- select {
- case m, ok := <-ch:
- if !ok {
- return
- }
- if !open {
- if s, err = d.Dial(); err != nil {
- panic(err)
- }
- open = true
- }
- if err := gomail.Send(s, m); err != nil {
- log.Print(err)
- }
- // Close the connection to the SMTP server if no email was sent in
- // the last 30 seconds.
- case <-time.After(30 * time.Second):
- if open {
- if err := s.Close(); err != nil {
- panic(err)
- }
- open = false
- }
- }
- }
- }()
-
- // Use the channel in your program to send emails.
-
- // Close the channel to stop the mail daemon.
- close(ch)
-}
-
-// Efficiently send a customized newsletter to a list of recipients.
-func Example_newsletter() {
- // The list of recipients.
- var list []struct {
- Name string
- Address string
- }
-
- d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
- s, err := d.Dial()
- if err != nil {
- panic(err)
- }
-
- m := gomail.NewMessage()
- for _, r := range list {
- m.SetHeader("From", "no-reply@example.com")
- m.SetAddressHeader("To", r.Address, r.Name)
- m.SetHeader("Subject", "Newsletter #1")
- m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))
-
- if err := gomail.Send(s, m); err != nil {
- log.Printf("Could not send email to %q: %v", r.Address, err)
- }
- m.Reset()
- }
-}
-
-// Send an email using a local SMTP server.
-func Example_noAuth() {
- m := gomail.NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetHeader("Subject", "Hello!")
- m.SetBody("text/plain", "Hello!")
-
- d := gomail.Dialer{Host: "localhost", Port: 587}
- if err := d.DialAndSend(m); err != nil {
- panic(err)
- }
-}
-
-// Send an email using an API or postfix.
-func Example_noSMTP() {
- m := gomail.NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetHeader("Subject", "Hello!")
- m.SetBody("text/plain", "Hello!")
-
- s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
- // Implements you email-sending function, for example by calling
- // an API, or running postfix, etc.
- fmt.Println("From:", from)
- fmt.Println("To:", to)
- return nil
- })
-
- if err := gomail.Send(s, m); err != nil {
- panic(err)
- }
- // Output:
- // From: from@example.com
- // To: [to@example.com]
-}
-
-var m *gomail.Message
-
-func ExampleSetCopyFunc() {
- m.Attach("foo.txt", gomail.SetCopyFunc(func(w io.Writer) error {
- _, err := w.Write([]byte("Content of foo.txt"))
- return err
- }))
-}
-
-func ExampleSetHeader() {
- h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
- m.Attach("foo.jpg", gomail.SetHeader(h))
-}
-
-func ExampleMessage_AddAlternative() {
- m.SetBody("text/plain", "Hello!")
- m.AddAlternative("text/html", "<p>Hello!</p>")
-}
-
-func ExampleMessage_AddAlternativeWriter() {
- t := template.Must(template.New("example").Parse("Hello {{.}}!"))
- m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
- return t.Execute(w, "Bob")
- })
-}
-
-func ExampleMessage_Attach() {
- m.Attach("/tmp/image.jpg")
-}
-
-func ExampleMessage_Embed() {
- m.Embed("/tmp/image.jpg")
- m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
-}
-
-func ExampleMessage_FormatAddress() {
- m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
-}
-
-func ExampleMessage_FormatDate() {
- m.SetHeaders(map[string][]string{
- "X-Date": {m.FormatDate(time.Now())},
- })
-}
-
-func ExampleMessage_SetAddressHeader() {
- m.SetAddressHeader("To", "bob@example.com", "Bob")
-}
-
-func ExampleMessage_SetBody() {
- m.SetBody("text/plain", "Hello!")
-}
-
-func ExampleMessage_SetDateHeader() {
- m.SetDateHeader("X-Date", time.Now())
-}
-
-func ExampleMessage_SetHeader() {
- m.SetHeader("Subject", "Hello!")
-}
-
-func ExampleMessage_SetHeaders() {
- m.SetHeaders(map[string][]string{
- "From": {m.FormatAddress("alex@example.com", "Alex")},
- "To": {"bob@example.com", "cora@example.com"},
- "Subject": {"Hello"},
- })
-}
-
-func ExampleSetCharset() {
- m = gomail.NewMessage(gomail.SetCharset("ISO-8859-1"))
-}
-
-func ExampleSetEncoding() {
- m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64))
-}
diff --git a/vendor/gopkg.in/gomail.v2/message_test.go b/vendor/gopkg.in/gomail.v2/message_test.go
deleted file mode 100644
index fdd9ff9bd..000000000
--- a/vendor/gopkg.in/gomail.v2/message_test.go
+++ /dev/null
@@ -1,630 +0,0 @@
-package gomail
-
-import (
- "bytes"
- "encoding/base64"
- "io"
- "io/ioutil"
- "path/filepath"
- "regexp"
- "strconv"
- "strings"
- "testing"
- "time"
-)
-
-func init() {
- now = func() time.Time {
- return time.Date(2014, 06, 25, 17, 46, 0, 0, time.UTC)
- }
-}
-
-type message struct {
- from string
- to []string
- content string
-}
-
-func TestMessage(t *testing.T) {
- m := NewMessage()
- m.SetAddressHeader("From", "from@example.com", "Señor From")
- m.SetHeader("To", m.FormatAddress("to@example.com", "Señor To"), "tobis@example.com")
- m.SetAddressHeader("Cc", "cc@example.com", "A, B")
- m.SetAddressHeader("X-To", "ccbis@example.com", "à, b")
- m.SetDateHeader("X-Date", now())
- m.SetHeader("X-Date-2", m.FormatDate(now()))
- m.SetHeader("Subject", "¡Hola, señor!")
- m.SetHeaders(map[string][]string{
- "X-Headers": {"Test", "Café"},
- })
- m.SetBody("text/plain", "¡Hola, señor!")
-
- want := &message{
- from: "from@example.com",
- to: []string{
- "to@example.com",
- "tobis@example.com",
- "cc@example.com",
- },
- content: "From: =?UTF-8?q?Se=C3=B1or_From?= <from@example.com>\r\n" +
- "To: =?UTF-8?q?Se=C3=B1or_To?= <to@example.com>, tobis@example.com\r\n" +
- "Cc: \"A, B\" <cc@example.com>\r\n" +
- "X-To: =?UTF-8?b?w6AsIGI=?= <ccbis@example.com>\r\n" +
- "X-Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" +
- "X-Date-2: Wed, 25 Jun 2014 17:46:00 +0000\r\n" +
- "X-Headers: Test, =?UTF-8?q?Caf=C3=A9?=\r\n" +
- "Subject: =?UTF-8?q?=C2=A1Hola,_se=C3=B1or!?=\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "=C2=A1Hola, se=C3=B1or!",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestBodyWriter(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
- _, err := w.Write([]byte("Test message"))
- return err
- })
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test message",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestCustomMessage(t *testing.T) {
- m := NewMessage(SetCharset("ISO-8859-1"), SetEncoding(Base64))
- m.SetHeaders(map[string][]string{
- "From": {"from@example.com"},
- "To": {"to@example.com"},
- "Subject": {"Café"},
- })
- m.SetBody("text/html", "¡Hola, señor!")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Subject: =?ISO-8859-1?b?Q2Fmw6k=?=\r\n" +
- "Content-Type: text/html; charset=ISO-8859-1\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- "wqFIb2xhLCBzZcOxb3Ih",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestUnencodedMessage(t *testing.T) {
- m := NewMessage(SetEncoding(Unencoded))
- m.SetHeaders(map[string][]string{
- "From": {"from@example.com"},
- "To": {"to@example.com"},
- "Subject": {"Café"},
- })
- m.SetBody("text/html", "¡Hola, señor!")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Subject: =?UTF-8?q?Caf=C3=A9?=\r\n" +
- "Content-Type: text/html; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: 8bit\r\n" +
- "\r\n" +
- "¡Hola, señor!",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestRecipients(t *testing.T) {
- m := NewMessage()
- m.SetHeaders(map[string][]string{
- "From": {"from@example.com"},
- "To": {"to@example.com"},
- "Cc": {"cc@example.com"},
- "Bcc": {"bcc1@example.com", "bcc2@example.com"},
- "Subject": {"Hello!"},
- })
- m.SetBody("text/plain", "Test message")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com", "cc@example.com", "bcc1@example.com", "bcc2@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Cc: cc@example.com\r\n" +
- "Subject: Hello!\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test message",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestAlternative(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", "¡Hola, señor!")
- m.AddAlternative("text/html", "¡<b>Hola</b>, <i>señor</i>!</h1>")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/alternative; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "=C2=A1Hola, se=C3=B1or!\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: text/html; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "=C2=A1<b>Hola</b>, <i>se=C3=B1or</i>!</h1>\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 1, want)
-}
-
-func TestAttachmentOnly(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.Attach(mockCopyFile("/tmp/test.pdf"))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: application/pdf; name=\"test.pdf\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")),
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestAttachment(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", "Test")
- m.Attach(mockCopyFile("/tmp/test.pdf"))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/mixed; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/pdf; name=\"test.pdf\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 1, want)
-}
-
-func TestAttachmentsOnly(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.Attach(mockCopyFile("/tmp/test.pdf"))
- m.Attach(mockCopyFile("/tmp/test.zip"))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/mixed; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/pdf; name=\"test.pdf\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/zip; name=\"test.zip\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.zip\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.zip")) + "\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 1, want)
-}
-
-func TestAttachments(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", "Test")
- m.Attach(mockCopyFile("/tmp/test.pdf"))
- m.Attach(mockCopyFile("/tmp/test.zip"))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/mixed; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/pdf; name=\"test.pdf\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/zip; name=\"test.zip\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.zip\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.zip")) + "\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 1, want)
-}
-
-func TestEmbedded(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.Embed(mockCopyFileWithHeader(m, "image1.jpg", map[string][]string{"Content-ID": {"<test-content-id>"}}))
- m.Embed(mockCopyFile("image2.jpg"))
- m.SetBody("text/plain", "Test")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/related; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: image/jpeg; name=\"image1.jpg\"\r\n" +
- "Content-Disposition: inline; filename=\"image1.jpg\"\r\n" +
- "Content-ID: <test-content-id>\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of image1.jpg")) + "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: image/jpeg; name=\"image2.jpg\"\r\n" +
- "Content-Disposition: inline; filename=\"image2.jpg\"\r\n" +
- "Content-ID: <image2.jpg>\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of image2.jpg")) + "\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 1, want)
-}
-
-func TestFullMessage(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", "¡Hola, señor!")
- m.AddAlternative("text/html", "¡<b>Hola</b>, <i>señor</i>!</h1>")
- m.Attach(mockCopyFile("test.pdf"))
- m.Embed(mockCopyFile("image.jpg"))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: multipart/mixed; boundary=_BOUNDARY_1_\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: multipart/related; boundary=_BOUNDARY_2_\r\n" +
- "\r\n" +
- "--_BOUNDARY_2_\r\n" +
- "Content-Type: multipart/alternative; boundary=_BOUNDARY_3_\r\n" +
- "\r\n" +
- "--_BOUNDARY_3_\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "=C2=A1Hola, se=C3=B1or!\r\n" +
- "--_BOUNDARY_3_\r\n" +
- "Content-Type: text/html; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "=C2=A1<b>Hola</b>, <i>se=C3=B1or</i>!</h1>\r\n" +
- "--_BOUNDARY_3_--\r\n" +
- "\r\n" +
- "--_BOUNDARY_2_\r\n" +
- "Content-Type: image/jpeg; name=\"image.jpg\"\r\n" +
- "Content-Disposition: inline; filename=\"image.jpg\"\r\n" +
- "Content-ID: <image.jpg>\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of image.jpg")) + "\r\n" +
- "--_BOUNDARY_2_--\r\n" +
- "\r\n" +
- "--_BOUNDARY_1_\r\n" +
- "Content-Type: application/pdf; name=\"test.pdf\"\r\n" +
- "Content-Disposition: attachment; filename=\"test.pdf\"\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- base64.StdEncoding.EncodeToString([]byte("Content of test.pdf")) + "\r\n" +
- "--_BOUNDARY_1_--\r\n",
- }
-
- testMessage(t, m, 3, want)
-
- want = &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- "Test reset",
- }
- m.Reset()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", "Test reset")
- testMessage(t, m, 0, want)
-}
-
-func TestQpLineLength(t *testing.T) {
- m := NewMessage()
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain",
- strings.Repeat("0", 76)+"\r\n"+
- strings.Repeat("0", 75)+"à\r\n"+
- strings.Repeat("0", 74)+"à\r\n"+
- strings.Repeat("0", 73)+"à\r\n"+
- strings.Repeat("0", 72)+"à\r\n"+
- strings.Repeat("0", 75)+"\r\n"+
- strings.Repeat("0", 76)+"\n")
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- strings.Repeat("0", 75) + "=\r\n0\r\n" +
- strings.Repeat("0", 75) + "=\r\n=C3=A0\r\n" +
- strings.Repeat("0", 74) + "=\r\n=C3=A0\r\n" +
- strings.Repeat("0", 73) + "=\r\n=C3=A0\r\n" +
- strings.Repeat("0", 72) + "=C3=\r\n=A0\r\n" +
- strings.Repeat("0", 75) + "\r\n" +
- strings.Repeat("0", 75) + "=\r\n0\r\n",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func TestBase64LineLength(t *testing.T) {
- m := NewMessage(SetCharset("UTF-8"), SetEncoding(Base64))
- m.SetHeader("From", "from@example.com")
- m.SetHeader("To", "to@example.com")
- m.SetBody("text/plain", strings.Repeat("0", 58))
-
- want := &message{
- from: "from@example.com",
- to: []string{"to@example.com"},
- content: "From: from@example.com\r\n" +
- "To: to@example.com\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: base64\r\n" +
- "\r\n" +
- strings.Repeat("MDAw", 19) + "\r\nMA==",
- }
-
- testMessage(t, m, 0, want)
-}
-
-func testMessage(t *testing.T, m *Message, bCount int, want *message) {
- err := Send(stubSendMail(t, bCount, want), m)
- if err != nil {
- t.Error(err)
- }
-}
-
-func stubSendMail(t *testing.T, bCount int, want *message) SendFunc {
- return func(from string, to []string, m io.WriterTo) error {
- if from != want.from {
- t.Fatalf("Invalid from, got %q, want %q", from, want.from)
- }
-
- if len(to) != len(want.to) {
- t.Fatalf("Invalid recipient count, \ngot %d: %q\nwant %d: %q",
- len(to), to,
- len(want.to), want.to,
- )
- }
- for i := range want.to {
- if to[i] != want.to[i] {
- t.Fatalf("Invalid recipient, got %q, want %q",
- to[i], want.to[i],
- )
- }
- }
-
- buf := new(bytes.Buffer)
- _, err := m.WriteTo(buf)
- if err != nil {
- t.Error(err)
- }
- got := buf.String()
- wantMsg := string("Mime-Version: 1.0\r\n" +
- "Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" +
- want.content)
- if bCount > 0 {
- boundaries := getBoundaries(t, bCount, got)
- for i, b := range boundaries {
- wantMsg = strings.Replace(wantMsg, "_BOUNDARY_"+strconv.Itoa(i+1)+"_", b, -1)
- }
- }
-
- compareBodies(t, got, wantMsg)
-
- return nil
- }
-}
-
-func compareBodies(t *testing.T, got, want string) {
- // We cannot do a simple comparison since the ordering of headers' fields
- // is random.
- gotLines := strings.Split(got, "\r\n")
- wantLines := strings.Split(want, "\r\n")
-
- // We only test for too many lines, missing lines are tested after
- if len(gotLines) > len(wantLines) {
- t.Fatalf("Message has too many lines, \ngot %d:\n%s\nwant %d:\n%s", len(gotLines), got, len(wantLines), want)
- }
-
- isInHeader := true
- headerStart := 0
- for i, line := range wantLines {
- if line == gotLines[i] {
- if line == "" {
- isInHeader = false
- } else if !isInHeader && len(line) > 2 && line[:2] == "--" {
- isInHeader = true
- headerStart = i + 1
- }
- continue
- }
-
- if !isInHeader {
- missingLine(t, line, got, want)
- }
-
- isMissing := true
- for j := headerStart; j < len(gotLines); j++ {
- if gotLines[j] == "" {
- break
- }
- if gotLines[j] == line {
- isMissing = false
- break
- }
- }
- if isMissing {
- missingLine(t, line, got, want)
- }
- }
-}
-
-func missingLine(t *testing.T, line, got, want string) {
- t.Fatalf("Missing line %q\ngot:\n%s\nwant:\n%s", line, got, want)
-}
-
-func getBoundaries(t *testing.T, count int, m string) []string {
- if matches := boundaryRegExp.FindAllStringSubmatch(m, count); matches != nil {
- boundaries := make([]string, count)
- for i, match := range matches {
- boundaries[i] = match[1]
- }
- return boundaries
- }
-
- t.Fatal("Boundary not found in body")
- return []string{""}
-}
-
-var boundaryRegExp = regexp.MustCompile("boundary=(\\w+)")
-
-func mockCopyFile(name string) (string, FileSetting) {
- return name, SetCopyFunc(func(w io.Writer) error {
- _, err := w.Write([]byte("Content of " + filepath.Base(name)))
- return err
- })
-}
-
-func mockCopyFileWithHeader(m *Message, name string, h map[string][]string) (string, FileSetting, FileSetting) {
- name, f := mockCopyFile(name)
- return name, f, SetHeader(h)
-}
-
-func BenchmarkFull(b *testing.B) {
- discardFunc := SendFunc(func(from string, to []string, m io.WriterTo) error {
- _, err := m.WriteTo(ioutil.Discard)
- return err
- })
-
- m := NewMessage()
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- m.SetAddressHeader("From", "from@example.com", "Señor From")
- m.SetHeaders(map[string][]string{
- "To": {"to@example.com"},
- "Cc": {"cc@example.com"},
- "Bcc": {"bcc1@example.com", "bcc2@example.com"},
- "Subject": {"¡Hola, señor!"},
- })
- m.SetBody("text/plain", "¡Hola, señor!")
- m.AddAlternative("text/html", "<p>¡Hola, señor!</p>")
- m.Attach(mockCopyFile("benchmark.txt"))
- m.Embed(mockCopyFile("benchmark.jpg"))
-
- if err := Send(discardFunc, m); err != nil {
- panic(err)
- }
- m.Reset()
- }
-}
diff --git a/vendor/gopkg.in/gomail.v2/send_test.go b/vendor/gopkg.in/gomail.v2/send_test.go
deleted file mode 100644
index ba59cd3dc..000000000
--- a/vendor/gopkg.in/gomail.v2/send_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package gomail
-
-import (
- "bytes"
- "io"
- "reflect"
- "testing"
-)
-
-const (
- testTo1 = "to1@example.com"
- testTo2 = "to2@example.com"
- testFrom = "from@example.com"
- testBody = "Test message"
- testMsg = "To: " + testTo1 + ", " + testTo2 + "\r\n" +
- "From: " + testFrom + "\r\n" +
- "Mime-Version: 1.0\r\n" +
- "Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" +
- "Content-Type: text/plain; charset=UTF-8\r\n" +
- "Content-Transfer-Encoding: quoted-printable\r\n" +
- "\r\n" +
- testBody
-)
-
-type mockSender SendFunc
-
-func (s mockSender) Send(from string, to []string, msg io.WriterTo) error {
- return s(from, to, msg)
-}
-
-type mockSendCloser struct {
- mockSender
- close func() error
-}
-
-func (s *mockSendCloser) Close() error {
- return s.close()
-}
-
-func TestSend(t *testing.T) {
- s := &mockSendCloser{
- mockSender: stubSend(t, testFrom, []string{testTo1, testTo2}, testMsg),
- close: func() error {
- t.Error("Close() should not be called in Send()")
- return nil
- },
- }
- if err := Send(s, getTestMessage()); err != nil {
- t.Errorf("Send(): %v", err)
- }
-}
-
-func getTestMessage() *Message {
- m := NewMessage()
- m.SetHeader("From", testFrom)
- m.SetHeader("To", testTo1, testTo2)
- m.SetBody("text/plain", testBody)
-
- return m
-}
-
-func stubSend(t *testing.T, wantFrom string, wantTo []string, wantBody string) mockSender {
- return func(from string, to []string, msg io.WriterTo) error {
- if from != wantFrom {
- t.Errorf("invalid from, got %q, want %q", from, wantFrom)
- }
- if !reflect.DeepEqual(to, wantTo) {
- t.Errorf("invalid to, got %v, want %v", to, wantTo)
- }
-
- buf := new(bytes.Buffer)
- _, err := msg.WriteTo(buf)
- if err != nil {
- t.Fatal(err)
- }
- compareBodies(t, buf.String(), wantBody)
-
- return nil
- }
-}
diff --git a/vendor/gopkg.in/gomail.v2/smtp_test.go b/vendor/gopkg.in/gomail.v2/smtp_test.go
deleted file mode 100644
index c8503489b..000000000
--- a/vendor/gopkg.in/gomail.v2/smtp_test.go
+++ /dev/null
@@ -1,254 +0,0 @@
-package gomail
-
-import (
- "bytes"
- "crypto/tls"
- "io"
- "net"
- "net/smtp"
- "reflect"
- "testing"
-)
-
-const (
- testPort = 587
- testSSLPort = 465
-)
-
-var (
- testTLSConn = &tls.Conn{}
- testConfig = &tls.Config{InsecureSkipVerify: true}
-)
-
-func TestDialer(t *testing.T) {
- d := NewPlainDialer(testHost, testPort, "user", "pwd")
- testSendMail(t, d, []string{
- "Extension STARTTLS",
- "StartTLS",
- "Extension AUTH",
- "Auth",
- "Mail " + testFrom,
- "Rcpt " + testTo1,
- "Rcpt " + testTo2,
- "Data",
- "Write message",
- "Close writer",
- "Quit",
- "Close",
- })
-}
-
-func TestDialerSSL(t *testing.T) {
- d := NewPlainDialer(testHost, testSSLPort, "user", "pwd")
- testSendMail(t, d, []string{
- "Extension AUTH",
- "Auth",
- "Mail " + testFrom,
- "Rcpt " + testTo1,
- "Rcpt " + testTo2,
- "Data",
- "Write message",
- "Close writer",
- "Quit",
- "Close",
- })
-}
-
-func TestDialerConfig(t *testing.T) {
- d := NewPlainDialer(testHost, testPort, "user", "pwd")
- d.TLSConfig = testConfig
- testSendMail(t, d, []string{
- "Extension STARTTLS",
- "StartTLS",
- "Extension AUTH",
- "Auth",
- "Mail " + testFrom,
- "Rcpt " + testTo1,
- "Rcpt " + testTo2,
- "Data",
- "Write message",
- "Close writer",
- "Quit",
- "Close",
- })
-}
-
-func TestDialerSSLConfig(t *testing.T) {
- d := NewPlainDialer(testHost, testSSLPort, "user", "pwd")
- d.TLSConfig = testConfig
- testSendMail(t, d, []string{
- "Extension AUTH",
- "Auth",
- "Mail " + testFrom,
- "Rcpt " + testTo1,
- "Rcpt " + testTo2,
- "Data",
- "Write message",
- "Close writer",
- "Quit",
- "Close",
- })
-}
-
-func TestDialerNoAuth(t *testing.T) {
- d := &Dialer{
- Host: testHost,
- Port: testPort,
- }
- testSendMail(t, d, []string{
- "Extension STARTTLS",
- "StartTLS",
- "Mail " + testFrom,
- "Rcpt " + testTo1,
- "Rcpt " + testTo2,
- "Data",
- "Write message",
- "Close writer",
- "Quit",
- "Close",
- })
-}
-
-type mockClient struct {
- t *testing.T
- i int
- want []string
- addr string
- auth smtp.Auth
- config *tls.Config
-}
-
-func (c *mockClient) Extension(ext string) (bool, string) {
- c.do("Extension " + ext)
- return true, ""
-}
-
-func (c *mockClient) StartTLS(config *tls.Config) error {
- assertConfig(c.t, config, c.config)
- c.do("StartTLS")
- return nil
-}
-
-func (c *mockClient) Auth(a smtp.Auth) error {
- assertAuth(c.t, a, c.auth)
- c.do("Auth")
- return nil
-}
-
-func (c *mockClient) Mail(from string) error {
- c.do("Mail " + from)
- return nil
-}
-
-func (c *mockClient) Rcpt(to string) error {
- c.do("Rcpt " + to)
- return nil
-}
-
-func (c *mockClient) Data() (io.WriteCloser, error) {
- c.do("Data")
- return &mockWriter{c: c, want: testMsg}, nil
-}
-
-func (c *mockClient) Quit() error {
- c.do("Quit")
- return nil
-}
-
-func (c *mockClient) Close() error {
- c.do("Close")
- return nil
-}
-
-func (c *mockClient) do(cmd string) {
- if c.i >= len(c.want) {
- c.t.Fatalf("Invalid command %q", cmd)
- }
-
- if cmd != c.want[c.i] {
- c.t.Fatalf("Invalid command, got %q, want %q", cmd, c.want[c.i])
- }
- c.i++
-}
-
-type mockWriter struct {
- want string
- c *mockClient
- buf bytes.Buffer
-}
-
-func (w *mockWriter) Write(p []byte) (int, error) {
- if w.buf.Len() == 0 {
- w.c.do("Write message")
- }
- w.buf.Write(p)
- return len(p), nil
-}
-
-func (w *mockWriter) Close() error {
- compareBodies(w.c.t, w.buf.String(), w.want)
- w.c.do("Close writer")
- return nil
-}
-
-func testSendMail(t *testing.T, d *Dialer, want []string) {
- testClient := &mockClient{
- t: t,
- want: want,
- addr: addr(d.Host, d.Port),
- auth: testAuth,
- config: d.TLSConfig,
- }
-
- smtpDial = func(addr string) (smtpClient, error) {
- assertAddr(t, addr, testClient.addr)
- return testClient, nil
- }
-
- tlsDial = func(network, addr string, config *tls.Config) (*tls.Conn, error) {
- if network != "tcp" {
- t.Errorf("Invalid network, got %q, want tcp", network)
- }
- assertAddr(t, addr, testClient.addr)
- assertConfig(t, config, testClient.config)
- return testTLSConn, nil
- }
-
- newClient = func(conn net.Conn, host string) (smtpClient, error) {
- if conn != testTLSConn {
- t.Error("Invalid TLS connection used")
- }
- if host != testHost {
- t.Errorf("Invalid host, got %q, want %q", host, testHost)
- }
- return testClient, nil
- }
-
- if err := d.DialAndSend(getTestMessage()); err != nil {
- t.Error(err)
- }
-}
-
-func assertAuth(t *testing.T, got, want smtp.Auth) {
- if !reflect.DeepEqual(got, want) {
- t.Errorf("Invalid auth, got %#v, want %#v", got, want)
- }
-}
-
-func assertAddr(t *testing.T, got, want string) {
- if got != want {
- t.Errorf("Invalid addr, got %q, want %q", got, want)
- }
-}
-
-func assertConfig(t *testing.T, got, want *tls.Config) {
- if want == nil {
- want = &tls.Config{ServerName: testHost}
- }
- if got.ServerName != want.ServerName {
- t.Errorf("Invalid field ServerName in config, got %q, want %q", got.ServerName, want.ServerName)
- }
- if got.InsecureSkipVerify != want.InsecureSkipVerify {
- t.Errorf("Invalid field InsecureSkipVerify in config, got %v, want %v", got.InsecureSkipVerify, want.InsecureSkipVerify)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/.travis.yml b/vendor/gopkg.in/olivere/elastic.v5/.travis.yml
index 9658f873a..82b36e7d0 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/.travis.yml
+++ b/vendor/gopkg.in/olivere/elastic.v5/.travis.yml
@@ -2,8 +2,8 @@ sudo: required
language: go
script: go test -race -v . ./config
go:
- - 1.8.x
- - 1.9.x
+ - "1.9.x"
+ - "1.10.x"
# - tip
matrix:
allow_failures:
@@ -12,4 +12,5 @@ services:
- docker
before_install:
- sudo sysctl -w vm.max_map_count=262144
- - docker run -d --rm -p 9200:9200 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" -e "bootstrap.memory_lock=true" -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch-oss:6.2.1 elasticsearch -Enetwork.host=_local_,_site_ -Enetwork.publish_host=_local_
+ - docker run --rm --privileged=true -p 9200:9200 -p 9300:9300 -e "bootstrap.memory_lock=true" -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch:5.6.8 elasticsearch -Expack.security.enabled=false -Escript.inline=true -Escript.stored=true -Escript.file=true -Enetwork.host=_local_,_site_ -Enetwork.publish_host=_local_ >& /dev/null &
+ - sleep 30
diff --git a/vendor/gopkg.in/olivere/elastic.v5/CHANGELOG-6.0.md b/vendor/gopkg.in/olivere/elastic.v5/CHANGELOG-6.0.md
deleted file mode 100644
index 277925929..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/CHANGELOG-6.0.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Changes from 5.0 to 6.0
-
-See [breaking changes](https://www.elastic.co/guide/en/elasticsearch/reference/master/breaking-changes-6.0.html).
-
-## _all removed
-
-6.0 has removed support for the `_all` field.
-
-## Boolean values coerced
-
-Only use `true` or `false` for boolean values, not `0` or `1` or `on` or `off`.
-
-## Single Type Indices
-
-Notice that 6.0 and future versions will default to single type indices, i.e. you may not use multiple types when e.g. adding an index with a mapping.
-
-See [here for details](https://www.elastic.co/guide/en/elasticsearch/reference/6.x/removal-of-types.html#_what_are_mapping_types).
-
diff --git a/vendor/gopkg.in/olivere/elastic.v5/CONTRIBUTORS b/vendor/gopkg.in/olivere/elastic.v5/CONTRIBUTORS
index ba06dac29..73a471f39 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/CONTRIBUTORS
+++ b/vendor/gopkg.in/olivere/elastic.v5/CONTRIBUTORS
@@ -24,6 +24,7 @@ Arquivei [@arquivei](https://github.com/arquivei)
arthurgustin [@arthurgustin](https://github.com/arthurgustin)
Benjamin Fernandes [@LotharSee](https://github.com/LotharSee)
Benjamin Zarzycki [@kf6nux](https://github.com/kf6nux)
+Boris Popovschi [@Zyqsempai](https://github.com/Zyqsempai)
Braden Bassingthwaite [@bbassingthwaite-va](https://github.com/bbassingthwaite-va)
Brady Love [@bradylove](https://github.com/bradylove)
Bryan Conklin [@bmconklin](https://github.com/bmconklin)
@@ -47,6 +48,7 @@ Evan Shaw [@edsrzf](https://github.com/edsrzf)
Fanfan [@wenpos](https://github.com/wenpos)
Faolan C-P [@fcheslack](https://github.com/fcheslack)
Filip Tepper [@filiptepper](https://github.com/filiptepper)
+Gaspard Douady [@plopik](https://github.com/plopik)
Gaylord Aulke [@blafasel42](https://github.com/blafasel42)
Gerhard Häring [@ghaering](https://github.com/ghaering)
Guilherme Silveira [@guilherme-santos](https://github.com/guilherme-santos)
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ISSUE_TEMPLATE.md b/vendor/gopkg.in/olivere/elastic.v5/ISSUE_TEMPLATE.md
index 88d66cc83..c5eb690a7 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ISSUE_TEMPLATE.md
+++ b/vendor/gopkg.in/olivere/elastic.v5/ISSUE_TEMPLATE.md
@@ -6,7 +6,6 @@ your issue/question without further inquiry. Thank you.
[ ] elastic.v2 (for Elasticsearch 1.x)
[ ] elastic.v3 (for Elasticsearch 2.x)
[ ] elastic.v5 (for Elasticsearch 5.x)
-[ ] elastic.v6 (for Elasticsearch 6.x)
### Please describe the expected behavior
diff --git a/vendor/gopkg.in/olivere/elastic.v5/README.md b/vendor/gopkg.in/olivere/elastic.v5/README.md
index d0cdd7821..30930ff22 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/README.md
+++ b/vendor/gopkg.in/olivere/elastic.v5/README.md
@@ -1,12 +1,10 @@
# Elastic
-**This is a development branch that is actively being worked on. DO NOT USE IN PRODUCTION!**
-
Elastic is an [Elasticsearch](http://www.elasticsearch.org/) client for the
[Go](http://www.golang.org/) programming language.
-[![Build Status](https://travis-ci.org/olivere/elastic.svg?branch=release-branch.v6)](https://travis-ci.org/olivere/elastic)
-[![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](http://godoc.org/github.com/olivere/elastic)
+[![Build Status](https://travis-ci.org/olivere/elastic.svg?branch=release-branch.v5)](https://travis-ci.org/olivere/elastic)
+[![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](http://godoc.org/gopkg.in/olivere/elastic.v5)
[![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/olivere/elastic/master/LICENSE)
See the [wiki](https://github.com/olivere/elastic/wiki) for additional information about Elastic.
@@ -14,46 +12,35 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for additional informati
## Releases
-**The release branches (e.g. [`release-branch.v6`](https://github.com/olivere/elastic/tree/release-branch.v6))
+**The release branches (e.g. [`release-branch.v5`](https://github.com/olivere/elastic/tree/release-branch.v5))
are actively being worked on and can break at any time.
-If you want to use stable versions of Elastic, please use a dependency manager like [dep](https://github.com/golang/dep).**
+If you want to use stable versions of Elastic, please use the packages released via [gopkg.in](https://gopkg.in).**
Here's the version matrix:
-Elasticsearch version | Elastic version | Package URL | Remarks |
-----------------------|------------------|-------------|---------|
-6.x                   | 6.0             | [`github.com/olivere/elastic`](https://github.com/olivere/elastic) ([source](https://github.com/olivere/elastic/tree/release-branch.v6) [doc](http://godoc.org/github.com/olivere/elastic)) | Use a dependency manager (see below).
-5.x | 5.0 | [`gopkg.in/olivere/elastic.v5`](https://gopkg.in/olivere/elastic.v5) ([source](https://github.com/olivere/elastic/tree/release-branch.v5) [doc](http://godoc.org/gopkg.in/olivere/elastic.v5)) | Actively maintained.
-2.x | 3.0 | [`gopkg.in/olivere/elastic.v3`](https://gopkg.in/olivere/elastic.v3) ([source](https://github.com/olivere/elastic/tree/release-branch.v3) [doc](http://godoc.org/gopkg.in/olivere/elastic.v3)) | Deprecated. Please update.
-1.x | 2.0 | [`gopkg.in/olivere/elastic.v2`](https://gopkg.in/olivere/elastic.v2) ([source](https://github.com/olivere/elastic/tree/release-branch.v2) [doc](http://godoc.org/gopkg.in/olivere/elastic.v2)) | Deprecated. Please update.
-0.9-1.3 | 1.0 | [`gopkg.in/olivere/elastic.v1`](https://gopkg.in/olivere/elastic.v1) ([source](https://github.com/olivere/elastic/tree/release-branch.v1) [doc](http://godoc.org/gopkg.in/olivere/elastic.v1)) | Deprecated. Please update.
+Elasticsearch version | Elastic version -| Package URL
+----------------------|------------------|------------
+5.x | 5.0 | [`gopkg.in/olivere/elastic.v5`](https://gopkg.in/olivere/elastic.v5) ([source](https://github.com/olivere/elastic/tree/release-branch.v5) [doc](http://godoc.org/gopkg.in/olivere/elastic.v5))
+2.x | 3.0 | [`gopkg.in/olivere/elastic.v3`](https://gopkg.in/olivere/elastic.v3) ([source](https://github.com/olivere/elastic/tree/release-branch.v3) [doc](http://godoc.org/gopkg.in/olivere/elastic.v3))
+1.x | 2.0 | [`gopkg.in/olivere/elastic.v2`](https://gopkg.in/olivere/elastic.v2) ([source](https://github.com/olivere/elastic/tree/release-branch.v2) [doc](http://godoc.org/gopkg.in/olivere/elastic.v2))
+0.9-1.3 | 1.0 | [`gopkg.in/olivere/elastic.v1`](https://gopkg.in/olivere/elastic.v1) ([source](https://github.com/olivere/elastic/tree/release-branch.v1) [doc](http://godoc.org/gopkg.in/olivere/elastic.v1))
**Example:**
-You have installed Elasticsearch 6.0.0 and want to use Elastic.
-As listed above, you should use Elastic 6.0.
+You have installed Elasticsearch 5.0.0 and want to use Elastic.
+As listed above, you should use Elastic 5.0.
+So you first install the stable release of Elastic 5.0 from gopkg.in.
-To use the required version of Elastic in your application, it is strongly
-advised to use a tool like
-[dep](https://github.com/golang/dep)
-or
-[Glide](https://glide.sh/)
-to manage that dependency. Make sure to use a version such as `^6.0.0`.
+```sh
+$ go get gopkg.in/olivere/elastic.v5
+```
-To use Elastic, simply import:
+You then import it with this import path:
```go
-import "github.com/olivere/elastic"
+import elastic "gopkg.in/olivere/elastic.v5"
```
-### Elastic 6.0
-
-Elastic 6.0 targets Elasticsearch 6.x which was [released on 14th November 2017](https://www.elastic.co/blog/elasticsearch-6-0-0-released).
-
-Notice that there are will be a lot of [breaking changes in Elasticsearch 6.0](https://www.elastic.co/guide/en/elasticsearch/reference/6.0/breaking-changes-6.0.html)
-and we used this as an opportunity to [clean up and refactor Elastic](https://github.com/olivere/elastic/blob/release-branch.v6/CHANGELOG-6.0.md)
-as we did in the transition from earlier versions of Elastic.
-
### Elastic 5.0
Elastic 5.0 targets Elasticsearch 5.0.0 and later. Elasticsearch 5.0.0 was
@@ -120,7 +107,7 @@ The client connects to Elasticsearch on `http://127.0.0.1:9200` by default.
You typically create one client for your app. Here's a complete example of
creating a client, creating an index, adding a document, executing a search etc.
-An example is available [here](https://olivere.github.io/elastic/).
+An example is available [here](https://olivere.github.io/elastic/)
Here's a [link to a complete working example for v3](https://gist.github.com/olivere/114347ff9d9cfdca7bdc0ecea8b82263).
@@ -148,7 +135,7 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Search
- [x] Search Template
- [ ] Multi Search Template
-- [ ] Search Shards API
+- [x] Search Shards API
- [x] Suggesters
- [x] Term Suggester
- [x] Phrase Suggester
@@ -156,10 +143,12 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Context Suggester
- [x] Multi Search API
- [x] Count API
-- [ ] Validate API
+- [ ] Search Exists API
+- [x] Validate API
- [x] Explain API
- [x] Profile API
- [x] Field Capabilities API
+- [x] Field Stats API
### Aggregations
@@ -168,7 +157,7 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Cardinality
- [x] Extended Stats
- [x] Geo Bounds
- - [ ] Geo Centroid
+ - [x] Geo Centroid
- [x] Max
- [x] Min
- [x] Percentiles
@@ -179,11 +168,11 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Top Hits
- [x] Value Count
- Bucket Aggregations
- - [ ] Adjacency Matrix
+ - [x] Adjacency Matrix
- [x] Children
- [x] Date Histogram
- [x] Date Range
- - [ ] Diversified Sampler
+ - [x] Diversified Sampler
- [x] Filter
- [x] Filters
- [x] Geo Distance
@@ -197,9 +186,7 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Reverse Nested
- [x] Sampler
- [x] Significant Terms
- - [x] Significant Text
- [x] Terms
- - [x] Composite
- Pipeline Aggregations
- [x] Avg Bucket
- [x] Derivative
@@ -213,7 +200,6 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Cumulative Sum
- [x] Bucket Script
- [x] Bucket Selector
- - [ ] Bucket Sort
- [x] Serial Differencing
- [x] Matrix Aggregations
- [x] Matrix Stats
@@ -236,17 +222,17 @@ See the [wiki](https://github.com/olivere/elastic/wiki) for more details.
- [x] Update Indices Settings
- [x] Get Settings
- [x] Analyze
- - [x] Explain Analyze
- [x] Index Templates
+- [ ] Shadow Replica Indices
- [x] Indices Stats
- [x] Indices Segments
- [ ] Indices Recovery
- [ ] Indices Shard Stores
- [ ] Clear Cache
- [x] Flush
- - [x] Synced Flush
- [x] Refresh
- [x] Force Merge
+- [ ] Upgrade
### cat APIs
@@ -269,7 +255,6 @@ The cat APIs are not implemented as of now. We think they are better suited for
- [ ] cat shards
- [ ] cat segments
- [ ] cat snapshots
-- [ ] cat templates
### Cluster APIs
@@ -281,8 +266,6 @@ The cat APIs are not implemented as of now. We think they are better suited for
- [ ] Cluster Update Settings
- [x] Nodes Stats
- [x] Nodes Info
-- [ ] Nodes Feature Usage
-- [ ] Remote Cluster Info
- [x] Task Management API
- [ ] Nodes hot_threads
- [ ] Cluster Allocation Explain API
@@ -302,7 +285,6 @@ The cat APIs are not implemented as of now. We think they are better suited for
- Term level queries
- [x] Term Query
- [x] Terms Query
- - [x] Terms Set Query
- [x] Range Query
- [x] Exists Query
- [x] Prefix Query
@@ -317,6 +299,7 @@ The cat APIs are not implemented as of now. We think they are better suited for
- [x] Dis Max Query
- [x] Function Score Query
- [x] Boosting Query
+ - [x] Indices Query
- Joining queries
- [x] Nested Query
- [x] Has Child Query
@@ -326,9 +309,12 @@ The cat APIs are not implemented as of now. We think they are better suited for
- [ ] GeoShape Query
- [x] Geo Bounding Box Query
- [x] Geo Distance Query
+ - [ ] Geo Distance Range Query
- [x] Geo Polygon Query
+ - [ ] Geohash Cell Query
- Specialized queries
- [x] More Like This Query
+ - [x] Template Query
- [x] Script Query
- [x] Percolate Query
- Span queries
@@ -348,7 +334,7 @@ The cat APIs are not implemented as of now. We think they are better suited for
- Snapshot and Restore
- [x] Repositories
- - [x] Snapshot
+ - [ ] Snapshot
- [ ] Restore
- [ ] Snapshot status
- [ ] Monitoring snapshot/restore status
diff --git a/vendor/gopkg.in/olivere/elastic.v5/acknowledged_response.go b/vendor/gopkg.in/olivere/elastic.v5/acknowledged_response.go
index 2045ab85e..83f954f44 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/acknowledged_response.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/acknowledged_response.go
@@ -7,7 +7,5 @@ package elastic
// AcknowledgedResponse is returned from various APIs. It simply indicates
// whether the operation is ack'd or not.
type AcknowledgedResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/backoff_test.go b/vendor/gopkg.in/olivere/elastic.v5/backoff_test.go
deleted file mode 100644
index eae168a12..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/backoff_test.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package elastic
-
-import (
- "math/rand"
- "testing"
- "time"
-)
-
-func TestZeroBackoff(t *testing.T) {
- b := ZeroBackoff{}
- _, ok := b.Next(0)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
-}
-
-func TestStopBackoff(t *testing.T) {
- b := StopBackoff{}
- _, ok := b.Next(0)
- if ok {
- t.Fatalf("expected %v, got %v", false, ok)
- }
-}
-
-func TestConstantBackoff(t *testing.T) {
- b := NewConstantBackoff(time.Second)
- d, ok := b.Next(0)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if d != time.Second {
- t.Fatalf("expected %v, got %v", time.Second, d)
- }
-}
-
-func TestSimpleBackoff(t *testing.T) {
- var tests = []struct {
- Duration time.Duration
- Continue bool
- }{
- // #0
- {
- Duration: 1 * time.Millisecond,
- Continue: true,
- },
- // #1
- {
- Duration: 2 * time.Millisecond,
- Continue: true,
- },
- // #2
- {
- Duration: 7 * time.Millisecond,
- Continue: true,
- },
- // #3
- {
- Duration: 0,
- Continue: false,
- },
- // #4
- {
- Duration: 0,
- Continue: false,
- },
- }
-
- b := NewSimpleBackoff(1, 2, 7)
-
- for i, tt := range tests {
- d, ok := b.Next(i)
- if got, want := ok, tt.Continue; got != want {
- t.Fatalf("#%d: expected %v, got %v", i, want, got)
- }
- if got, want := d, tt.Duration; got != want {
- t.Fatalf("#%d: expected %v, got %v", i, want, got)
- }
- }
-}
-
-func TestExponentialBackoff(t *testing.T) {
- rand.Seed(time.Now().UnixNano())
-
- min := time.Duration(8) * time.Millisecond
- max := time.Duration(256) * time.Millisecond
- b := NewExponentialBackoff(min, max)
-
- between := func(value time.Duration, a, b int) bool {
- x := int(value / time.Millisecond)
- return a <= x && x <= b
- }
-
- got, ok := b.Next(0)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if !between(got, 8, 256) {
- t.Errorf("expected [%v..%v], got %v", 8, 256, got)
- }
-
- got, ok = b.Next(1)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if !between(got, 8, 256) {
- t.Errorf("expected [%v..%v], got %v", 8, 256, got)
- }
-
- got, ok = b.Next(2)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if !between(got, 8, 256) {
- t.Errorf("expected [%v..%v], got %v", 8, 256, got)
- }
-
- got, ok = b.Next(3)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if !between(got, 8, 256) {
- t.Errorf("expected [%v..%v], got %v", 8, 256, got)
- }
-
- got, ok = b.Next(4)
- if !ok {
- t.Fatalf("expected %v, got %v", true, ok)
- }
- if !between(got, 8, 256) {
- t.Errorf("expected [%v..%v], got %v", 8, 256, got)
- }
-
- if _, ok := b.Next(5); ok {
- t.Fatalf("expected %v, got %v", false, ok)
- }
-
- if _, ok = b.Next(6); ok {
- t.Fatalf("expected %v, got %v", false, ok)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk.go b/vendor/gopkg.in/olivere/elastic.v5/bulk.go
index f4228294f..452f5c394 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk.go
@@ -11,7 +11,7 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// BulkService allows for batching bulk requests and sending them to
@@ -23,7 +23,7 @@ import (
// reuse BulkService to send many batches. You do not have to create a new
// BulkService for each batch.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for more details.
type BulkService struct {
client *Client
@@ -243,7 +243,7 @@ func (s *BulkService) Do(ctx context.Context) (*BulkResponse, error) {
}
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
+ res, err := s.client.PerformRequestWithOptions(ctx, PerformRequestOptions{
Method: "POST",
Path: path,
Params: params,
@@ -320,12 +320,10 @@ type BulkResponseItem struct {
Type string `json:"_type,omitempty"`
Id string `json:"_id,omitempty"`
Version int64 `json:"_version,omitempty"`
- Result string `json:"result,omitempty"`
- Shards *shardsInfo `json:"_shards,omitempty"`
- SeqNo int64 `json:"_seq_no,omitempty"`
- PrimaryTerm int64 `json:"_primary_term,omitempty"`
Status int `json:"status,omitempty"`
+ Result string `json:"result,omitempty"`
ForcedRefresh bool `json:"forced_refresh,omitempty"`
+ Found bool `json:"found,omitempty"`
Error *ErrorDetails `json:"error,omitempty"`
GetResult *GetResult `json:"get,omitempty"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request.go
index e6c98c553..6a6bfa7fe 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request.go
@@ -16,7 +16,7 @@ import (
// BulkDeleteRequest is a request to remove a document from Elasticsearch.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
type BulkDeleteRequest struct {
BulkableRequest
@@ -38,13 +38,13 @@ type bulkDeleteRequestCommand map[string]bulkDeleteRequestCommandOp
//easyjson:json
type bulkDeleteRequestCommandOp struct {
+ Id string `json:"_id,omitempty"`
Index string `json:"_index,omitempty"`
+ Parent string `json:"_parent,omitempty"`
+ Routing string `json:"_routing,omitempty"`
Type string `json:"_type,omitempty"`
- Id string `json:"_id,omitempty"`
- Parent string `json:"parent,omitempty"`
- Routing string `json:"routing,omitempty"`
- Version int64 `json:"version,omitempty"`
- VersionType string `json:"version_type,omitempty"`
+ Version int64 `json:"_version,omitempty"`
+ VersionType string `json:"_version_type,omitempty"`
}
// NewBulkDeleteRequest returns a new BulkDeleteRequest.
@@ -109,7 +109,7 @@ func (r *BulkDeleteRequest) Version(version int64) *BulkDeleteRequest {
}
// VersionType can be "internal" (default), "external", "external_gte",
-// or "external_gt".
+// "external_gt", or "force".
func (r *BulkDeleteRequest) VersionType(versionType string) *BulkDeleteRequest {
r.versionType = versionType
r.source = nil
@@ -128,7 +128,7 @@ func (r *BulkDeleteRequest) String() string {
// 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/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
func (r *BulkDeleteRequest) Source() ([]string, error) {
if r.source != nil {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_easyjson.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_easyjson.go
index df3452ce6..16dc83f7b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_easyjson.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_easyjson.go
@@ -17,7 +17,7 @@ var (
_ easyjson.Marshaler
)
-func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDeleteRequestCommandOp) {
+func easyjson8092efb6DecodeGopkgInOlivereElasticV5(in *jlexer.Lexer, out *bulkDeleteRequestCommandOp) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
@@ -36,19 +36,19 @@ func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDe
continue
}
switch key {
- case "_index":
- out.Index = string(in.String())
- case "_type":
- out.Type = string(in.String())
case "_id":
out.Id = string(in.String())
- case "parent":
+ case "_index":
+ out.Index = string(in.String())
+ case "_parent":
out.Parent = string(in.String())
- case "routing":
+ case "_routing":
out.Routing = string(in.String())
- case "version":
+ case "_type":
+ out.Type = string(in.String())
+ case "_version":
out.Version = int64(in.Int64())
- case "version_type":
+ case "_version_type":
out.VersionType = string(in.String())
default:
in.SkipRecursive()
@@ -60,62 +60,62 @@ func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDe
in.Consumed()
}
}
-func easyjson8092efb6EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkDeleteRequestCommandOp) {
+func easyjson8092efb6EncodeGopkgInOlivereElasticV5(out *jwriter.Writer, in bulkDeleteRequestCommandOp) {
out.RawByte('{')
first := true
_ = first
- if in.Index != "" {
- const prefix string = ",\"_index\":"
+ if in.Id != "" {
+ const prefix string = ",\"_id\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Index))
+ out.String(string(in.Id))
}
- if in.Type != "" {
- const prefix string = ",\"_type\":"
+ if in.Index != "" {
+ const prefix string = ",\"_index\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Type))
+ out.String(string(in.Index))
}
- if in.Id != "" {
- const prefix string = ",\"_id\":"
+ if in.Parent != "" {
+ const prefix string = ",\"_parent\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Id))
+ out.String(string(in.Parent))
}
- if in.Parent != "" {
- const prefix string = ",\"parent\":"
+ if in.Routing != "" {
+ const prefix string = ",\"_routing\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Parent))
+ out.String(string(in.Routing))
}
- if in.Routing != "" {
- const prefix string = ",\"routing\":"
+ if in.Type != "" {
+ const prefix string = ",\"_type\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Routing))
+ out.String(string(in.Type))
}
if in.Version != 0 {
- const prefix string = ",\"version\":"
+ const prefix string = ",\"_version\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -125,7 +125,7 @@ func easyjson8092efb6EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkD
out.Int64(int64(in.Version))
}
if in.VersionType != "" {
- const prefix string = ",\"version_type\":"
+ const prefix string = ",\"_version_type\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -140,27 +140,27 @@ func easyjson8092efb6EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkD
// MarshalJSON supports json.Marshaler interface
func (v bulkDeleteRequestCommandOp) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson8092efb6EncodeGithubComOlivereElastic(&w, v)
+ easyjson8092efb6EncodeGopkgInOlivereElasticV5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkDeleteRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson8092efb6EncodeGithubComOlivereElastic(w, v)
+ easyjson8092efb6EncodeGopkgInOlivereElasticV5(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkDeleteRequestCommandOp) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson8092efb6DecodeGithubComOlivereElastic(&r, v)
+ easyjson8092efb6DecodeGopkgInOlivereElasticV5(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkDeleteRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson8092efb6DecodeGithubComOlivereElastic(l, v)
+ easyjson8092efb6DecodeGopkgInOlivereElasticV5(l, v)
}
-func easyjson8092efb6DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkDeleteRequestCommand) {
+func easyjson8092efb6DecodeGopkgInOlivereElasticV51(in *jlexer.Lexer, out *bulkDeleteRequestCommand) {
isTopLevel := in.IsStart()
if in.IsNull() {
in.Skip()
@@ -185,7 +185,7 @@ func easyjson8092efb6DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkD
in.Consumed()
}
}
-func easyjson8092efb6EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkDeleteRequestCommand) {
+func easyjson8092efb6EncodeGopkgInOlivereElasticV51(out *jwriter.Writer, in bulkDeleteRequestCommand) {
if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 {
out.RawString(`null`)
} else {
@@ -208,23 +208,23 @@ func easyjson8092efb6EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk
// MarshalJSON supports json.Marshaler interface
func (v bulkDeleteRequestCommand) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson8092efb6EncodeGithubComOlivereElastic1(&w, v)
+ easyjson8092efb6EncodeGopkgInOlivereElasticV51(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkDeleteRequestCommand) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson8092efb6EncodeGithubComOlivereElastic1(w, v)
+ easyjson8092efb6EncodeGopkgInOlivereElasticV51(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkDeleteRequestCommand) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson8092efb6DecodeGithubComOlivereElastic1(&r, v)
+ easyjson8092efb6DecodeGopkgInOlivereElasticV51(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkDeleteRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson8092efb6DecodeGithubComOlivereElastic1(l, v)
+ easyjson8092efb6DecodeGopkgInOlivereElasticV51(l, v)
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_test.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_test.go
deleted file mode 100644
index 8635e34d1..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_delete_request_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestBulkDeleteRequestSerialization(t *testing.T) {
- tests := []struct {
- Request BulkableRequest
- Expected []string
- }{
- // #0
- {
- Request: NewBulkDeleteRequest().Index("index1").Type("doc").Id("1"),
- Expected: []string{
- `{"delete":{"_index":"index1","_type":"doc","_id":"1"}}`,
- },
- },
- // #1
- {
- Request: NewBulkDeleteRequest().Index("index1").Type("doc").Id("1").Parent("2"),
- Expected: []string{
- `{"delete":{"_index":"index1","_type":"doc","_id":"1","parent":"2"}}`,
- },
- },
- // #2
- {
- Request: NewBulkDeleteRequest().Index("index1").Type("doc").Id("1").Routing("3"),
- Expected: []string{
- `{"delete":{"_index":"index1","_type":"doc","_id":"1","routing":"3"}}`,
- },
- },
- }
-
- for i, test := range tests {
- lines, err := test.Request.Source()
- if err != nil {
- t.Fatalf("case #%d: expected no error, got: %v", i, err)
- }
- if lines == nil {
- t.Fatalf("case #%d: expected lines, got nil", i)
- }
- if len(lines) != len(test.Expected) {
- t.Fatalf("case #%d: expected %d lines, got %d", i, len(test.Expected), len(lines))
- }
- for j, line := range lines {
- if line != test.Expected[j] {
- t.Errorf("case #%d: expected line #%d to be %s, got: %s", i, j, test.Expected[j], line)
- }
- }
- }
-}
-
-var bulkDeleteRequestSerializationResult string
-
-func BenchmarkBulkDeleteRequestSerialization(b *testing.B) {
- b.Run("stdlib", func(b *testing.B) {
- r := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
- benchmarkBulkDeleteRequestSerialization(b, r.UseEasyJSON(false))
- })
- b.Run("easyjson", func(b *testing.B) {
- r := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
- benchmarkBulkDeleteRequestSerialization(b, r.UseEasyJSON(true))
- })
-}
-
-func benchmarkBulkDeleteRequestSerialization(b *testing.B, r *BulkDeleteRequest) {
- var s string
- for n := 0; n < b.N; n++ {
- s = r.String()
- r.source = nil // Don't let caching spoil the benchmark
- }
- bulkDeleteRequestSerializationResult = s // ensure the compiler doesn't optimize
- b.ReportAllocs()
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request.go
index 321d2e25a..70497a046 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request.go
@@ -14,7 +14,7 @@ import (
// BulkIndexRequest is a request to add a document to Elasticsearch.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
type BulkIndexRequest struct {
BulkableRequest
@@ -29,6 +29,7 @@ type BulkIndexRequest struct {
doc interface{}
pipeline string
retryOnConflict *int
+ ttl string
source []string
@@ -40,15 +41,15 @@ type bulkIndexRequestCommand map[string]bulkIndexRequestCommandOp
//easyjson:json
type bulkIndexRequestCommandOp struct {
- Index string `json:"_index,omitempty"`
- Id string `json:"_id,omitempty"`
- Type string `json:"_type,omitempty"`
- Parent string `json:"parent,omitempty"`
- // RetryOnConflict is "_retry_on_conflict" for 6.0 and "retry_on_conflict" for 6.1+.
- RetryOnConflict *int `json:"retry_on_conflict,omitempty"`
- Routing string `json:"routing,omitempty"`
- Version int64 `json:"version,omitempty"`
- VersionType string `json:"version_type,omitempty"`
+ Id string `json:"_id,omitempty"`
+ Index string `json:"_index,omitempty"`
+ TTL string `json:"_ttl,omitempty"`
+ Type string `json:"_type,omitempty"`
+ Parent string `json:"_parent,omitempty"`
+ RetryOnConflict *int `json:"_retry_on_conflict,omitempty"`
+ Routing string `json:"_routing,omitempty"`
+ Version int64 `json:"_version,omitempty"`
+ VersionType string `json:"_version_type,omitempty"`
Pipeline string `json:"pipeline,omitempty"`
}
@@ -95,7 +96,7 @@ func (r *BulkIndexRequest) Id(id string) *BulkIndexRequest {
// OpType specifies if this request should follow create-only or upsert
// behavior. This follows the OpType of the standard document index API.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-index_.html#operation-type
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#operation-type
// for details.
func (r *BulkIndexRequest) OpType(opType string) *BulkIndexRequest {
r.opType = opType
@@ -128,7 +129,7 @@ func (r *BulkIndexRequest) Version(version int64) *BulkIndexRequest {
// VersionType specifies how versions are created. It can be e.g. internal,
// external, external_gte, or force.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-index_.html#index-versioning
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#index-versioning
// for details.
func (r *BulkIndexRequest) VersionType(versionType string) *BulkIndexRequest {
r.versionType = versionType
@@ -150,6 +151,13 @@ func (r *BulkIndexRequest) RetryOnConflict(retryOnConflict int) *BulkIndexReques
return r
}
+// TTL is an expiration time for the document.
+func (r *BulkIndexRequest) TTL(ttl string) *BulkIndexRequest {
+ r.ttl = ttl
+ r.source = nil
+ return r
+}
+
// Pipeline to use while processing the request.
func (r *BulkIndexRequest) Pipeline(pipeline string) *BulkIndexRequest {
r.pipeline = pipeline
@@ -169,7 +177,7 @@ func (r *BulkIndexRequest) String() string {
// Source returns the on-wire representation of the index request,
// split into an action-and-meta-data line and an (optional) source line.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
func (r *BulkIndexRequest) Source() ([]string, error) {
// { "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
@@ -191,6 +199,7 @@ func (r *BulkIndexRequest) Source() ([]string, error) {
Version: r.version,
VersionType: r.versionType,
RetryOnConflict: r.retryOnConflict,
+ TTL: r.ttl,
Pipeline: r.pipeline,
}
command := bulkIndexRequestCommand{
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_easyjson.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_easyjson.go
index f8792978f..6ee19fbec 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_easyjson.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_easyjson.go
@@ -17,7 +17,7 @@ var (
_ easyjson.Marshaler
)
-func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIndexRequestCommandOp) {
+func easyjson9de0fcbfDecodeGopkgInOlivereElasticV5(in *jlexer.Lexer, out *bulkIndexRequestCommandOp) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
@@ -36,15 +36,17 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIn
continue
}
switch key {
- case "_index":
- out.Index = string(in.String())
case "_id":
out.Id = string(in.String())
+ case "_index":
+ out.Index = string(in.String())
+ case "_ttl":
+ out.TTL = string(in.String())
case "_type":
out.Type = string(in.String())
- case "parent":
+ case "_parent":
out.Parent = string(in.String())
- case "retry_on_conflict":
+ case "_retry_on_conflict":
if in.IsNull() {
in.Skip()
out.RetryOnConflict = nil
@@ -54,11 +56,11 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIn
}
*out.RetryOnConflict = int(in.Int())
}
- case "routing":
+ case "_routing":
out.Routing = string(in.String())
- case "version":
+ case "_version":
out.Version = int64(in.Int64())
- case "version_type":
+ case "_version_type":
out.VersionType = string(in.String())
case "pipeline":
out.Pipeline = string(in.String())
@@ -72,10 +74,20 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIn
in.Consumed()
}
}
-func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkIndexRequestCommandOp) {
+func easyjson9de0fcbfEncodeGopkgInOlivereElasticV5(out *jwriter.Writer, in bulkIndexRequestCommandOp) {
out.RawByte('{')
first := true
_ = first
+ if in.Id != "" {
+ const prefix string = ",\"_id\":"
+ if first {
+ first = false
+ out.RawString(prefix[1:])
+ } else {
+ out.RawString(prefix)
+ }
+ out.String(string(in.Id))
+ }
if in.Index != "" {
const prefix string = ",\"_index\":"
if first {
@@ -86,15 +98,15 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
}
out.String(string(in.Index))
}
- if in.Id != "" {
- const prefix string = ",\"_id\":"
+ if in.TTL != "" {
+ const prefix string = ",\"_ttl\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Id))
+ out.String(string(in.TTL))
}
if in.Type != "" {
const prefix string = ",\"_type\":"
@@ -107,7 +119,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
out.String(string(in.Type))
}
if in.Parent != "" {
- const prefix string = ",\"parent\":"
+ const prefix string = ",\"_parent\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -117,7 +129,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
out.String(string(in.Parent))
}
if in.RetryOnConflict != nil {
- const prefix string = ",\"retry_on_conflict\":"
+ const prefix string = ",\"_retry_on_conflict\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -127,7 +139,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
out.Int(int(*in.RetryOnConflict))
}
if in.Routing != "" {
- const prefix string = ",\"routing\":"
+ const prefix string = ",\"_routing\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -137,7 +149,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
out.String(string(in.Routing))
}
if in.Version != 0 {
- const prefix string = ",\"version\":"
+ const prefix string = ",\"_version\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -147,7 +159,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
out.Int64(int64(in.Version))
}
if in.VersionType != "" {
- const prefix string = ",\"version_type\":"
+ const prefix string = ",\"_version_type\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -172,27 +184,27 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI
// MarshalJSON supports json.Marshaler interface
func (v bulkIndexRequestCommandOp) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson9de0fcbfEncodeGithubComOlivereElastic(&w, v)
+ easyjson9de0fcbfEncodeGopkgInOlivereElasticV5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkIndexRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson9de0fcbfEncodeGithubComOlivereElastic(w, v)
+ easyjson9de0fcbfEncodeGopkgInOlivereElasticV5(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkIndexRequestCommandOp) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson9de0fcbfDecodeGithubComOlivereElastic(&r, v)
+ easyjson9de0fcbfDecodeGopkgInOlivereElasticV5(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkIndexRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson9de0fcbfDecodeGithubComOlivereElastic(l, v)
+ easyjson9de0fcbfDecodeGopkgInOlivereElasticV5(l, v)
}
-func easyjson9de0fcbfDecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkIndexRequestCommand) {
+func easyjson9de0fcbfDecodeGopkgInOlivereElasticV51(in *jlexer.Lexer, out *bulkIndexRequestCommand) {
isTopLevel := in.IsStart()
if in.IsNull() {
in.Skip()
@@ -217,7 +229,7 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkI
in.Consumed()
}
}
-func easyjson9de0fcbfEncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkIndexRequestCommand) {
+func easyjson9de0fcbfEncodeGopkgInOlivereElasticV51(out *jwriter.Writer, in bulkIndexRequestCommand) {
if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 {
out.RawString(`null`)
} else {
@@ -240,23 +252,23 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk
// MarshalJSON supports json.Marshaler interface
func (v bulkIndexRequestCommand) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson9de0fcbfEncodeGithubComOlivereElastic1(&w, v)
+ easyjson9de0fcbfEncodeGopkgInOlivereElasticV51(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkIndexRequestCommand) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson9de0fcbfEncodeGithubComOlivereElastic1(w, v)
+ easyjson9de0fcbfEncodeGopkgInOlivereElasticV51(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkIndexRequestCommand) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson9de0fcbfDecodeGithubComOlivereElastic1(&r, v)
+ easyjson9de0fcbfDecodeGopkgInOlivereElasticV51(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkIndexRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson9de0fcbfDecodeGithubComOlivereElastic1(l, v)
+ easyjson9de0fcbfDecodeGopkgInOlivereElasticV51(l, v)
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_test.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_test.go
deleted file mode 100644
index 79baf51fb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_index_request_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
- "time"
-)
-
-func TestBulkIndexRequestSerialization(t *testing.T) {
- tests := []struct {
- Request BulkableRequest
- Expected []string
- }{
- // #0
- {
- Request: NewBulkIndexRequest().Index("index1").Type("doc").Id("1").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"index":{"_index":"index1","_id":"1","_type":"doc"}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- // #1
- {
- Request: NewBulkIndexRequest().OpType("create").Index("index1").Type("doc").Id("1").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"create":{"_index":"index1","_id":"1","_type":"doc"}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- // #2
- {
- Request: NewBulkIndexRequest().OpType("index").Index("index1").Type("doc").Id("1").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"index":{"_index":"index1","_id":"1","_type":"doc"}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- // #3
- {
- Request: NewBulkIndexRequest().OpType("index").Index("index1").Type("doc").Id("1").RetryOnConflict(42).
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"index":{"_index":"index1","_id":"1","_type":"doc","retry_on_conflict":42}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- // #4
- {
- Request: NewBulkIndexRequest().OpType("index").Index("index1").Type("doc").Id("1").Pipeline("my_pipeline").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"index":{"_index":"index1","_id":"1","_type":"doc","pipeline":"my_pipeline"}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- // #5
- {
- Request: NewBulkIndexRequest().OpType("index").Index("index1").Type("doc").Id("1").
- Routing("123").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}),
- Expected: []string{
- `{"index":{"_index":"index1","_id":"1","_type":"doc","routing":"123"}}`,
- `{"user":"olivere","message":"","retweets":0,"created":"2014-01-18T23:59:58Z"}`,
- },
- },
- }
-
- for i, test := range tests {
- lines, err := test.Request.Source()
- if err != nil {
- t.Fatalf("case #%d: expected no error, got: %v", i, err)
- }
- if lines == nil {
- t.Fatalf("case #%d: expected lines, got nil", i)
- }
- if len(lines) != len(test.Expected) {
- t.Fatalf("case #%d: expected %d lines, got %d", i, len(test.Expected), len(lines))
- }
- for j, line := range lines {
- if line != test.Expected[j] {
- t.Errorf("case #%d: expected line #%d to be %s, got: %s", i, j, test.Expected[j], line)
- }
- }
- }
-}
-
-var bulkIndexRequestSerializationResult string
-
-func BenchmarkBulkIndexRequestSerialization(b *testing.B) {
- b.Run("stdlib", func(b *testing.B) {
- r := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)})
- benchmarkBulkIndexRequestSerialization(b, r.UseEasyJSON(false))
- })
- b.Run("easyjson", func(b *testing.B) {
- r := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").
- Doc(tweet{User: "olivere", Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)})
- benchmarkBulkIndexRequestSerialization(b, r.UseEasyJSON(true))
- })
-}
-
-func benchmarkBulkIndexRequestSerialization(b *testing.B, r *BulkIndexRequest) {
- var s string
- for n := 0; n < b.N; n++ {
- s = r.String()
- r.source = nil // Don't let caching spoil the benchmark
- }
- bulkIndexRequestSerializationResult = s // ensure the compiler doesn't optimize
- b.ReportAllocs()
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_processor.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_processor.go
index 6ee8a3dee..1b9263402 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_processor.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_processor.go
@@ -122,7 +122,7 @@ func (s *BulkProcessorService) Stats(wantStats bool) *BulkProcessorService {
return s
}
-// Backoff sets the backoff strategy to use for errors.
+// Backoff sets the backoff strategy to use for errors
func (s *BulkProcessorService) Backoff(backoff Backoff) *BulkProcessorService {
s.backoff = backoff
return s
@@ -462,7 +462,6 @@ func (w *bulkWorker) work(ctx context.Context) {
err = w.commit(ctx)
}
}
-
case <-w.flushC:
// Commit outstanding requests
if w.service.NumberOfActions() > 0 {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_processor_test.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_processor_test.go
deleted file mode 100644
index bb97ca217..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_processor_test.go
+++ /dev/null
@@ -1,425 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "fmt"
- "math/rand"
- "sync/atomic"
- "testing"
- "time"
-)
-
-func TestBulkProcessorDefaults(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- p := client.BulkProcessor()
- if p == nil {
- t.Fatalf("expected BulkProcessorService; got: %v", p)
- }
- if got, want := p.name, ""; got != want {
- t.Errorf("expected %q; got: %q", want, got)
- }
- if got, want := p.numWorkers, 1; got != want {
- t.Errorf("expected %d; got: %d", want, got)
- }
- if got, want := p.bulkActions, 1000; got != want {
- t.Errorf("expected %d; got: %d", want, got)
- }
- if got, want := p.bulkSize, 5*1024*1024; got != want {
- t.Errorf("expected %d; got: %d", want, got)
- }
- if got, want := p.flushInterval, time.Duration(0); got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := p.wantStats, false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if p.backoff == nil {
- t.Fatalf("expected non-nill backoff; got: %v", p.backoff)
- }
-}
-
-func TestBulkProcessorCommitOnBulkActions(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- testBulkProcessor(t,
- 10000,
- client.BulkProcessor().
- Name("Actions-1").
- Workers(1).
- BulkActions(100).
- BulkSize(-1),
- )
-
- testBulkProcessor(t,
- 10000,
- client.BulkProcessor().
- Name("Actions-2").
- Workers(2).
- BulkActions(100).
- BulkSize(-1),
- )
-}
-
-func TestBulkProcessorCommitOnBulkSize(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- testBulkProcessor(t,
- 10000,
- client.BulkProcessor().
- Name("Size-1").
- Workers(1).
- BulkActions(-1).
- BulkSize(64*1024),
- )
-
- testBulkProcessor(t,
- 10000,
- client.BulkProcessor().
- Name("Size-2").
- Workers(2).
- BulkActions(-1).
- BulkSize(64*1024),
- )
-}
-
-func TestBulkProcessorBasedOnFlushInterval(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- var beforeRequests int64
- var befores int64
- var afters int64
- var failures int64
- var afterRequests int64
-
- beforeFn := func(executionId int64, requests []BulkableRequest) {
- atomic.AddInt64(&beforeRequests, int64(len(requests)))
- atomic.AddInt64(&befores, 1)
- }
- afterFn := func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error) {
- atomic.AddInt64(&afters, 1)
- if err != nil {
- atomic.AddInt64(&failures, 1)
- }
- atomic.AddInt64(&afterRequests, int64(len(requests)))
- }
-
- svc := client.BulkProcessor().
- Name("FlushInterval-1").
- Workers(2).
- BulkActions(-1).
- BulkSize(-1).
- FlushInterval(1 * time.Second).
- Before(beforeFn).
- After(afterFn)
-
- p, err := svc.Do(context.Background())
- if err != nil {
- t.Fatal(err)
- }
-
- const numDocs = 1000 // low-enough number that flush should be invoked
-
- for i := 1; i <= numDocs; i++ {
- tweet := tweet{User: "olivere", Message: fmt.Sprintf("%d. %s", i, randomString(rand.Intn(64)))}
- request := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id(fmt.Sprintf("%d", i)).Doc(tweet)
- p.Add(request)
- }
-
- // Should flush at least once
- time.Sleep(2 * time.Second)
-
- err = p.Close()
- if err != nil {
- t.Fatal(err)
- }
-
- if p.stats.Flushed == 0 {
- t.Errorf("expected at least 1 flush; got: %d", p.stats.Flushed)
- }
- if got, want := beforeRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to before callback; got: %d", want, got)
- }
- if got, want := afterRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to after callback; got: %d", want, got)
- }
- if befores == 0 {
- t.Error("expected at least 1 call to before callback")
- }
- if afters == 0 {
- t.Error("expected at least 1 call to after callback")
- }
- if failures != 0 {
- t.Errorf("expected 0 calls to failure callback; got: %d", failures)
- }
-
- // Check number of documents that were bulk indexed
- _, err = p.c.Flush(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err := p.c.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != int64(numDocs) {
- t.Fatalf("expected %d documents; got: %d", numDocs, count)
- }
-}
-
-func TestBulkProcessorClose(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- var beforeRequests int64
- var befores int64
- var afters int64
- var failures int64
- var afterRequests int64
-
- beforeFn := func(executionId int64, requests []BulkableRequest) {
- atomic.AddInt64(&beforeRequests, int64(len(requests)))
- atomic.AddInt64(&befores, 1)
- }
- afterFn := func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error) {
- atomic.AddInt64(&afters, 1)
- if err != nil {
- atomic.AddInt64(&failures, 1)
- }
- atomic.AddInt64(&afterRequests, int64(len(requests)))
- }
-
- p, err := client.BulkProcessor().
- Name("FlushInterval-1").
- Workers(2).
- BulkActions(-1).
- BulkSize(-1).
- FlushInterval(30 * time.Second). // 30 seconds to flush
- Before(beforeFn).After(afterFn).
- Do(context.Background())
- if err != nil {
- t.Fatal(err)
- }
-
- const numDocs = 1000 // low-enough number that flush should be invoked
-
- for i := 1; i <= numDocs; i++ {
- tweet := tweet{User: "olivere", Message: fmt.Sprintf("%d. %s", i, randomString(rand.Intn(64)))}
- request := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id(fmt.Sprintf("%d", i)).Doc(tweet)
- p.Add(request)
- }
-
- // Should not flush because 30s > 1s
- time.Sleep(1 * time.Second)
-
- // Close should flush
- err = p.Close()
- if err != nil {
- t.Fatal(err)
- }
-
- if p.stats.Flushed != 0 {
- t.Errorf("expected no flush; got: %d", p.stats.Flushed)
- }
- if got, want := beforeRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to before callback; got: %d", want, got)
- }
- if got, want := afterRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to after callback; got: %d", want, got)
- }
- if befores == 0 {
- t.Error("expected at least 1 call to before callback")
- }
- if afters == 0 {
- t.Error("expected at least 1 call to after callback")
- }
- if failures != 0 {
- t.Errorf("expected 0 calls to failure callback; got: %d", failures)
- }
-
- // Check number of documents that were bulk indexed
- _, err = p.c.Flush(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err := p.c.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != int64(numDocs) {
- t.Fatalf("expected %d documents; got: %d", numDocs, count)
- }
-}
-
-func TestBulkProcessorFlush(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- p, err := client.BulkProcessor().
- Name("ManualFlush").
- Workers(10).
- BulkActions(-1).
- BulkSize(-1).
- FlushInterval(30 * time.Second). // 30 seconds to flush
- Stats(true).
- Do(context.Background())
- if err != nil {
- t.Fatal(err)
- }
-
- const numDocs = 100
-
- for i := 1; i <= numDocs; i++ {
- tweet := tweet{User: "olivere", Message: fmt.Sprintf("%d. %s", i, randomString(rand.Intn(64)))}
- request := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id(fmt.Sprintf("%d", i)).Doc(tweet)
- p.Add(request)
- }
-
- // Should not flush because 30s > 1s
- time.Sleep(1 * time.Second)
-
- // No flush yet
- stats := p.Stats()
- if stats.Flushed != 0 {
- t.Errorf("expected no flush; got: %d", p.stats.Flushed)
- }
-
- // Manual flush
- err = p.Flush()
- if err != nil {
- t.Fatal(err)
- }
-
- time.Sleep(1 * time.Second)
-
- // Now flushed
- stats = p.Stats()
- if got, want := p.stats.Flushed, int64(1); got != want {
- t.Errorf("expected %d flush; got: %d", want, got)
- }
-
- // Close should not start another flush
- err = p.Close()
- if err != nil {
- t.Fatal(err)
- }
-
- // Still 1 flush
- stats = p.Stats()
- if got, want := p.stats.Flushed, int64(1); got != want {
- t.Errorf("expected %d flush; got: %d", want, got)
- }
-
- // Check number of documents that were bulk indexed
- _, err = p.c.Flush(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err := p.c.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != int64(numDocs) {
- t.Fatalf("expected %d documents; got: %d", numDocs, count)
- }
-}
-
-// -- Helper --
-
-func testBulkProcessor(t *testing.T, numDocs int, svc *BulkProcessorService) {
- var beforeRequests int64
- var befores int64
- var afters int64
- var failures int64
- var afterRequests int64
-
- beforeFn := func(executionId int64, requests []BulkableRequest) {
- atomic.AddInt64(&beforeRequests, int64(len(requests)))
- atomic.AddInt64(&befores, 1)
- }
- afterFn := func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error) {
- atomic.AddInt64(&afters, 1)
- if err != nil {
- atomic.AddInt64(&failures, 1)
- }
- atomic.AddInt64(&afterRequests, int64(len(requests)))
- }
-
- p, err := svc.Before(beforeFn).After(afterFn).Stats(true).Do(context.Background())
- if err != nil {
- t.Fatal(err)
- }
-
- for i := 1; i <= numDocs; i++ {
- tweet := tweet{User: "olivere", Message: fmt.Sprintf("%07d. %s", i, randomString(1+rand.Intn(63)))}
- request := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id(fmt.Sprintf("%d", i)).Doc(tweet)
- p.Add(request)
- }
-
- err = p.Close()
- if err != nil {
- t.Fatal(err)
- }
-
- stats := p.Stats()
-
- if stats.Flushed != 0 {
- t.Errorf("expected no flush; got: %d", stats.Flushed)
- }
- if stats.Committed <= 0 {
- t.Errorf("expected committed > %d; got: %d", 0, stats.Committed)
- }
- if got, want := stats.Indexed, int64(numDocs); got != want {
- t.Errorf("expected indexed = %d; got: %d", want, got)
- }
- if got, want := stats.Created, int64(0); got != want {
- t.Errorf("expected created = %d; got: %d", want, got)
- }
- if got, want := stats.Updated, int64(0); got != want {
- t.Errorf("expected updated = %d; got: %d", want, got)
- }
- if got, want := stats.Deleted, int64(0); got != want {
- t.Errorf("expected deleted = %d; got: %d", want, got)
- }
- if got, want := stats.Succeeded, int64(numDocs); got != want {
- t.Errorf("expected succeeded = %d; got: %d", want, got)
- }
- if got, want := stats.Failed, int64(0); got != want {
- t.Errorf("expected failed = %d; got: %d", want, got)
- }
- if got, want := beforeRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to before callback; got: %d", want, got)
- }
- if got, want := afterRequests, int64(numDocs); got != want {
- t.Errorf("expected %d requests to after callback; got: %d", want, got)
- }
- if befores == 0 {
- t.Error("expected at least 1 call to before callback")
- }
- if afters == 0 {
- t.Error("expected at least 1 call to after callback")
- }
- if failures != 0 {
- t.Errorf("expected 0 calls to failure callback; got: %d", failures)
- }
-
- // Check number of documents that were bulk indexed
- _, err = p.c.Flush(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err := p.c.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != int64(numDocs) {
- t.Fatalf("expected %d documents; got: %d", numDocs, count)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_test.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_test.go
deleted file mode 100644
index f31ed6613..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_test.go
+++ /dev/null
@@ -1,600 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "math/rand"
- "net/http"
- "net/http/httptest"
- "testing"
-)
-
-func TestBulk(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Dancing all night long. Yeah."}
-
- index1Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(tweet1)
- index2Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("2").Doc(tweet2)
- delete1Req := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
-
- bulkRequest := client.Bulk()
- bulkRequest = bulkRequest.Add(index1Req)
- bulkRequest = bulkRequest.Add(index2Req)
- bulkRequest = bulkRequest.Add(delete1Req)
-
- if bulkRequest.NumberOfActions() != 3 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 3, bulkRequest.NumberOfActions())
- }
-
- bulkResponse, err := bulkRequest.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if bulkResponse == nil {
- t.Errorf("expected bulkResponse to be != nil; got nil")
- }
-
- if bulkRequest.NumberOfActions() != 0 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 0, bulkRequest.NumberOfActions())
- }
-
- // Document with Id="1" should not exist
- exists, err := client.Exists().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if exists {
- t.Errorf("expected exists %v; got %v", false, exists)
- }
-
- // Document with Id="2" should exist
- exists, err = client.Exists().Index(testIndexName).Type("doc").Id("2").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Errorf("expected exists %v; got %v", true, exists)
- }
-
- // Update
- updateDoc := struct {
- Retweets int `json:"retweets"`
- }{
- 42,
- }
- update1Req := NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("2").Doc(&updateDoc)
- bulkRequest = client.Bulk()
- bulkRequest = bulkRequest.Add(update1Req)
-
- if bulkRequest.NumberOfActions() != 1 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 1, bulkRequest.NumberOfActions())
- }
-
- bulkResponse, err = bulkRequest.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if bulkResponse == nil {
- t.Errorf("expected bulkResponse to be != nil; got nil")
- }
-
- if bulkRequest.NumberOfActions() != 0 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 0, bulkRequest.NumberOfActions())
- }
-
- // Document with Id="1" should have a retweets count of 42
- doc, err := client.Get().Index(testIndexName).Type("doc").Id("2").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if doc == nil {
- t.Fatal("expected doc to be != nil; got nil")
- }
- if !doc.Found {
- t.Fatalf("expected doc to be found; got found = %v", doc.Found)
- }
- if doc.Source == nil {
- t.Fatal("expected doc source to be != nil; got nil")
- }
- var updatedTweet tweet
- err = json.Unmarshal(*doc.Source, &updatedTweet)
- if err != nil {
- t.Fatal(err)
- }
- if updatedTweet.Retweets != 42 {
- t.Errorf("expected updated tweet retweets = %v; got %v", 42, updatedTweet.Retweets)
- }
-
- // Update with script
- update2Req := NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("2").
- RetryOnConflict(3).
- Script(NewScript("ctx._source.retweets += params.v").Param("v", 1))
- bulkRequest = client.Bulk()
- bulkRequest = bulkRequest.Add(update2Req)
- if bulkRequest.NumberOfActions() != 1 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 1, bulkRequest.NumberOfActions())
- }
- bulkResponse, err = bulkRequest.Refresh("wait_for").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if bulkResponse == nil {
- t.Errorf("expected bulkResponse to be != nil; got nil")
- }
-
- if bulkRequest.NumberOfActions() != 0 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 0, bulkRequest.NumberOfActions())
- }
-
- // Document with Id="1" should have a retweets count of 43
- doc, err = client.Get().Index(testIndexName).Type("doc").Id("2").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if doc == nil {
- t.Fatal("expected doc to be != nil; got nil")
- }
- if !doc.Found {
- t.Fatalf("expected doc to be found; got found = %v", doc.Found)
- }
- if doc.Source == nil {
- t.Fatal("expected doc source to be != nil; got nil")
- }
- err = json.Unmarshal(*doc.Source, &updatedTweet)
- if err != nil {
- t.Fatal(err)
- }
- if updatedTweet.Retweets != 43 {
- t.Errorf("expected updated tweet retweets = %v; got %v", 43, updatedTweet.Retweets)
- }
-}
-
-func TestBulkWithIndexSetOnClient(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Dancing all night long. Yeah."}
-
- index1Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(tweet1).Routing("1")
- index2Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("2").Doc(tweet2)
- delete1Req := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
-
- bulkRequest := client.Bulk().Index(testIndexName).Type("doc")
- bulkRequest = bulkRequest.Add(index1Req)
- bulkRequest = bulkRequest.Add(index2Req)
- bulkRequest = bulkRequest.Add(delete1Req)
-
- if bulkRequest.NumberOfActions() != 3 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 3, bulkRequest.NumberOfActions())
- }
-
- bulkResponse, err := bulkRequest.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if bulkResponse == nil {
- t.Errorf("expected bulkResponse to be != nil; got nil")
- }
-
- // Document with Id="1" should not exist
- exists, err := client.Exists().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if exists {
- t.Errorf("expected exists %v; got %v", false, exists)
- }
-
- // Document with Id="2" should exist
- exists, err = client.Exists().Index(testIndexName).Type("doc").Id("2").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Errorf("expected exists %v; got %v", true, exists)
- }
-}
-
-func TestBulkIndexDeleteUpdate(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- //client := setupTestClientAndCreateIndexAndLog(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Dancing all night long. Yeah."}
-
- index1Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(tweet1)
- index2Req := NewBulkIndexRequest().OpType("create").Index(testIndexName).Type("doc").Id("2").Doc(tweet2)
- delete1Req := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
- update2Req := NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("2").
- ReturnSource(true).
- Doc(struct {
- Retweets int `json:"retweets"`
- }{
- Retweets: 42,
- })
-
- bulkRequest := client.Bulk()
- bulkRequest = bulkRequest.Add(index1Req)
- bulkRequest = bulkRequest.Add(index2Req)
- bulkRequest = bulkRequest.Add(delete1Req)
- bulkRequest = bulkRequest.Add(update2Req)
-
- if bulkRequest.NumberOfActions() != 4 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 4, bulkRequest.NumberOfActions())
- }
-
- expected := `{"index":{"_index":"` + testIndexName + `","_id":"1","_type":"doc"}}
-{"user":"olivere","message":"Welcome to Golang and Elasticsearch.","retweets":0,"created":"0001-01-01T00:00:00Z"}
-{"create":{"_index":"` + testIndexName + `","_id":"2","_type":"doc"}}
-{"user":"sandrae","message":"Dancing all night long. Yeah.","retweets":0,"created":"0001-01-01T00:00:00Z"}
-{"delete":{"_index":"` + testIndexName + `","_type":"doc","_id":"1"}}
-{"update":{"_index":"` + testIndexName + `","_type":"doc","_id":"2"}}
-{"doc":{"retweets":42},"_source":true}
-`
- got, err := bulkRequest.bodyAsString()
- if err != nil {
- t.Fatalf("expected no error, got: %v", err)
- }
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-
- // Run the bulk request
- bulkResponse, err := bulkRequest.Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if bulkResponse == nil {
- t.Errorf("expected bulkResponse to be != nil; got nil")
- }
- if bulkResponse.Took == 0 {
- t.Errorf("expected took to be > 0; got %d", bulkResponse.Took)
- }
- if bulkResponse.Errors {
- t.Errorf("expected errors to be %v; got %v", false, bulkResponse.Errors)
- }
- if len(bulkResponse.Items) != 4 {
- t.Fatalf("expected 4 result items; got %d", len(bulkResponse.Items))
- }
-
- // Indexed actions
- indexed := bulkResponse.Indexed()
- if indexed == nil {
- t.Fatal("expected indexed to be != nil; got nil")
- }
- if len(indexed) != 1 {
- t.Fatalf("expected len(indexed) == %d; got %d", 1, len(indexed))
- }
- if indexed[0].Id != "1" {
- t.Errorf("expected indexed[0].Id == %s; got %s", "1", indexed[0].Id)
- }
- if indexed[0].Status != 201 {
- t.Errorf("expected indexed[0].Status == %d; got %d", 201, indexed[0].Status)
- }
-
- // Created actions
- created := bulkResponse.Created()
- if created == nil {
- t.Fatal("expected created to be != nil; got nil")
- }
- if len(created) != 1 {
- t.Fatalf("expected len(created) == %d; got %d", 1, len(created))
- }
- if created[0].Id != "2" {
- t.Errorf("expected created[0].Id == %s; got %s", "2", created[0].Id)
- }
- if created[0].Status != 201 {
- t.Errorf("expected created[0].Status == %d; got %d", 201, created[0].Status)
- }
- if want, have := "created", created[0].Result; want != have {
- t.Errorf("expected created[0].Result == %q; got %q", want, have)
- }
-
- // Deleted actions
- deleted := bulkResponse.Deleted()
- if deleted == nil {
- t.Fatal("expected deleted to be != nil; got nil")
- }
- if len(deleted) != 1 {
- t.Fatalf("expected len(deleted) == %d; got %d", 1, len(deleted))
- }
- if deleted[0].Id != "1" {
- t.Errorf("expected deleted[0].Id == %s; got %s", "1", deleted[0].Id)
- }
- if deleted[0].Status != 200 {
- t.Errorf("expected deleted[0].Status == %d; got %d", 200, deleted[0].Status)
- }
- if want, have := "deleted", deleted[0].Result; want != have {
- t.Errorf("expected deleted[0].Result == %q; got %q", want, have)
- }
-
- // Updated actions
- updated := bulkResponse.Updated()
- if updated == nil {
- t.Fatal("expected updated to be != nil; got nil")
- }
- if len(updated) != 1 {
- t.Fatalf("expected len(updated) == %d; got %d", 1, len(updated))
- }
- if updated[0].Id != "2" {
- t.Errorf("expected updated[0].Id == %s; got %s", "2", updated[0].Id)
- }
- if updated[0].Status != 200 {
- t.Errorf("expected updated[0].Status == %d; got %d", 200, updated[0].Status)
- }
- if updated[0].Version != 2 {
- t.Errorf("expected updated[0].Version == %d; got %d", 2, updated[0].Version)
- }
- if want, have := "updated", updated[0].Result; want != have {
- t.Errorf("expected updated[0].Result == %q; got %q", want, have)
- }
- if updated[0].GetResult == nil {
- t.Fatalf("expected updated[0].GetResult to be != nil; got nil")
- }
- if updated[0].GetResult.Source == nil {
- t.Fatalf("expected updated[0].GetResult.Source to be != nil; got nil")
- }
- if want, have := true, updated[0].GetResult.Found; want != have {
- t.Fatalf("expected updated[0].GetResult.Found to be != %v; got %v", want, have)
- }
- var doc tweet
- if err := json.Unmarshal(*updated[0].GetResult.Source, &doc); err != nil {
- t.Fatalf("expected to unmarshal updated[0].GetResult.Source; got %v", err)
- }
- if want, have := 42, doc.Retweets; want != have {
- t.Fatalf("expected updated tweet to have Retweets = %v; got %v", want, have)
- }
-
- // Succeeded actions
- succeeded := bulkResponse.Succeeded()
- if succeeded == nil {
- t.Fatal("expected succeeded to be != nil; got nil")
- }
- if len(succeeded) != 4 {
- t.Fatalf("expected len(succeeded) == %d; got %d", 4, len(succeeded))
- }
-
- // ById
- id1Results := bulkResponse.ById("1")
- if id1Results == nil {
- t.Fatal("expected id1Results to be != nil; got nil")
- }
- if len(id1Results) != 2 {
- t.Fatalf("expected len(id1Results) == %d; got %d", 2, len(id1Results))
- }
- if id1Results[0].Id != "1" {
- t.Errorf("expected id1Results[0].Id == %s; got %s", "1", id1Results[0].Id)
- }
- if id1Results[0].Status != 201 {
- t.Errorf("expected id1Results[0].Status == %d; got %d", 201, id1Results[0].Status)
- }
- if id1Results[0].Version != 1 {
- t.Errorf("expected id1Results[0].Version == %d; got %d", 1, id1Results[0].Version)
- }
- if id1Results[1].Id != "1" {
- t.Errorf("expected id1Results[1].Id == %s; got %s", "1", id1Results[1].Id)
- }
- if id1Results[1].Status != 200 {
- t.Errorf("expected id1Results[1].Status == %d; got %d", 200, id1Results[1].Status)
- }
- if id1Results[1].Version != 2 {
- t.Errorf("expected id1Results[1].Version == %d; got %d", 2, id1Results[1].Version)
- }
-}
-
-func TestFailedBulkRequests(t *testing.T) {
- js := `{
- "took" : 2,
- "errors" : true,
- "items" : [ {
- "index" : {
- "_index" : "elastic-test",
- "_type" : "doc",
- "_id" : "1",
- "_version" : 1,
- "status" : 201
- }
- }, {
- "create" : {
- "_index" : "elastic-test",
- "_type" : "doc",
- "_id" : "2",
- "_version" : 1,
- "status" : 423,
- "error" : {
- "type":"routing_missing_exception",
- "reason":"routing is required for [elastic-test2]/[comment]/[1]"
- }
- }
- }, {
- "delete" : {
- "_index" : "elastic-test",
- "_type" : "doc",
- "_id" : "1",
- "_version" : 2,
- "status" : 404,
- "found" : false
- }
- }, {
- "update" : {
- "_index" : "elastic-test",
- "_type" : "doc",
- "_id" : "2",
- "_version" : 2,
- "status" : 200
- }
- } ]
-}`
-
- var resp BulkResponse
- err := json.Unmarshal([]byte(js), &resp)
- if err != nil {
- t.Fatal(err)
- }
- failed := resp.Failed()
- if len(failed) != 2 {
- t.Errorf("expected %d failed items; got: %d", 2, len(failed))
- }
-}
-
-func TestBulkEstimatedSizeInBytes(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Dancing all night long. Yeah."}
-
- index1Req := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(tweet1)
- index2Req := NewBulkIndexRequest().OpType("create").Index(testIndexName).Type("doc").Id("2").Doc(tweet2)
- delete1Req := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
- update2Req := NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("2").
- Doc(struct {
- Retweets int `json:"retweets"`
- }{
- Retweets: 42,
- })
-
- bulkRequest := client.Bulk()
- bulkRequest = bulkRequest.Add(index1Req)
- bulkRequest = bulkRequest.Add(index2Req)
- bulkRequest = bulkRequest.Add(delete1Req)
- bulkRequest = bulkRequest.Add(update2Req)
-
- if bulkRequest.NumberOfActions() != 4 {
- t.Errorf("expected bulkRequest.NumberOfActions %d; got %d", 4, bulkRequest.NumberOfActions())
- }
-
- // The estimated size of the bulk request in bytes must be at least
- // the length of the body request.
- raw, err := bulkRequest.bodyAsString()
- if err != nil {
- t.Fatal(err)
- }
- rawlen := int64(len([]byte(raw)))
-
- if got, want := bulkRequest.EstimatedSizeInBytes(), rawlen; got < want {
- t.Errorf("expected an EstimatedSizeInBytes = %d; got: %v", want, got)
- }
-
- // Reset should also reset the calculated estimated byte size
- bulkRequest.reset()
-
- if got, want := bulkRequest.EstimatedSizeInBytes(), int64(0); got != want {
- t.Errorf("expected an EstimatedSizeInBytes = %d; got: %v", want, got)
- }
-}
-
-func TestBulkEstimateSizeInBytesLength(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- s := client.Bulk()
- r := NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1")
- s = s.Add(r)
- if got, want := s.estimateSizeInBytes(r), int64(1+len(r.String())); got != want {
- t.Fatalf("expected %d; got: %d", want, got)
- }
-}
-
-func TestBulkContentType(t *testing.T) {
- var header http.Header
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- header = r.Header
- fmt.Fprintln(w, `{}`)
- }))
- defer ts.Close()
-
- client, err := NewSimpleClient(SetURL(ts.URL))
- if err != nil {
- t.Fatal(err)
- }
- indexReq := NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."})
- if _, err := client.Bulk().Add(indexReq).Do(context.Background()); err != nil {
- t.Fatal(err)
- }
- if header == nil {
- t.Fatalf("expected header, got %v", header)
- }
- if want, have := "application/x-ndjson", header.Get("Content-Type"); want != have {
- t.Fatalf("Content-Type: want %q, have %q", want, have)
- }
-}
-
-// -- Benchmarks --
-
-var benchmarkBulkEstimatedSizeInBytes int64
-
-func BenchmarkBulkEstimatedSizeInBytesWith1Request(b *testing.B) {
- client := setupTestClientAndCreateIndex(b)
- s := client.Bulk()
- var result int64
- for n := 0; n < b.N; n++ {
- s = s.Add(NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(struct{ A string }{"1"}))
- s = s.Add(NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("1").Doc(struct{ A string }{"2"}))
- s = s.Add(NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1"))
- result = s.EstimatedSizeInBytes()
- s.reset()
- }
- b.ReportAllocs()
- benchmarkBulkEstimatedSizeInBytes = result // ensure the compiler doesn't optimize
-}
-
-func BenchmarkBulkEstimatedSizeInBytesWith100Requests(b *testing.B) {
- client := setupTestClientAndCreateIndex(b)
- s := client.Bulk()
- var result int64
- for n := 0; n < b.N; n++ {
- for i := 0; i < 100; i++ {
- s = s.Add(NewBulkIndexRequest().Index(testIndexName).Type("doc").Id("1").Doc(struct{ A string }{"1"}))
- s = s.Add(NewBulkUpdateRequest().Index(testIndexName).Type("doc").Id("1").Doc(struct{ A string }{"2"}))
- s = s.Add(NewBulkDeleteRequest().Index(testIndexName).Type("doc").Id("1"))
- }
- result = s.EstimatedSizeInBytes()
- s.reset()
- }
- b.ReportAllocs()
- benchmarkBulkEstimatedSizeInBytes = result // ensure the compiler doesn't optimize
-}
-
-func BenchmarkBulkAllocs(b *testing.B) {
- b.Run("1000 docs with 64 byte", func(b *testing.B) { benchmarkBulkAllocs(b, 64, 1000) })
- b.Run("1000 docs with 1 KiB", func(b *testing.B) { benchmarkBulkAllocs(b, 1024, 1000) })
- b.Run("1000 docs with 4 KiB", func(b *testing.B) { benchmarkBulkAllocs(b, 4096, 1000) })
- b.Run("1000 docs with 16 KiB", func(b *testing.B) { benchmarkBulkAllocs(b, 16*1024, 1000) })
- b.Run("1000 docs with 64 KiB", func(b *testing.B) { benchmarkBulkAllocs(b, 64*1024, 1000) })
- b.Run("1000 docs with 256 KiB", func(b *testing.B) { benchmarkBulkAllocs(b, 256*1024, 1000) })
- b.Run("1000 docs with 1 MiB", func(b *testing.B) { benchmarkBulkAllocs(b, 1024*1024, 1000) })
-}
-
-const (
- charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
-)
-
-func benchmarkBulkAllocs(b *testing.B, size, num int) {
- buf := make([]byte, size)
- for i := range buf {
- buf[i] = charset[rand.Intn(len(charset))]
- }
-
- s := &BulkService{}
- n := 0
- for {
- n++
- s = s.Add(NewBulkIndexRequest().Index("test").Type("doc").Id("1").Doc(struct {
- S string `json:"s"`
- }{
- S: string(buf),
- }))
- if n >= num {
- break
- }
- }
- for i := 0; i < b.N; i++ {
- s.bodyAsString()
- }
- b.ReportAllocs()
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request.go
index 50e5adb8f..bd05211b1 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request.go
@@ -14,7 +14,7 @@ import (
// BulkUpdateRequest is a request to update a document in Elasticsearch.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
type BulkUpdateRequest struct {
BulkableRequest
@@ -45,15 +45,14 @@ type bulkUpdateRequestCommand map[string]bulkUpdateRequestCommandOp
//easyjson:json
type bulkUpdateRequestCommandOp struct {
- Index string `json:"_index,omitempty"`
- Type string `json:"_type,omitempty"`
- Id string `json:"_id,omitempty"`
- Parent string `json:"parent,omitempty"`
- // RetryOnConflict is "_retry_on_conflict" for 6.0 and "retry_on_conflict" for 6.1+.
- RetryOnConflict *int `json:"retry_on_conflict,omitempty"`
- Routing string `json:"routing,omitempty"`
- Version int64 `json:"version,omitempty"`
- VersionType string `json:"version_type,omitempty"`
+ Id string `json:"_id,omitempty"`
+ Index string `json:"_index,omitempty"`
+ Type string `json:"_type,omitempty"`
+ Parent string `json:"_parent,omitempty"`
+ RetryOnConflict *int `json:"_retry_on_conflict,omitempty"`
+ Routing string `json:"_routing,omitempty"`
+ Version int64 `json:"_version,omitempty"`
+ VersionType string `json:"_version_type,omitempty"`
}
//easyjson:json
@@ -61,9 +60,9 @@ type bulkUpdateRequestCommandData struct {
DetectNoop *bool `json:"detect_noop,omitempty"`
Doc interface{} `json:"doc,omitempty"`
DocAsUpsert *bool `json:"doc_as_upsert,omitempty"`
+ Upsert interface{} `json:"upsert,omitempty"`
Script interface{} `json:"script,omitempty"`
ScriptedUpsert *bool `json:"scripted_upsert,omitempty"`
- Upsert interface{} `json:"upsert,omitempty"`
Source *bool `json:"_source,omitempty"`
}
@@ -120,8 +119,8 @@ func (r *BulkUpdateRequest) Parent(parent string) *BulkUpdateRequest {
}
// Script specifies an update script.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html#bulk-update
-// and https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-scripting.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html#bulk-update
+// and https://www.elastic.co/guide/en/elasticsearch/reference/5.2/modules-scripting.html
// for details.
func (r *BulkUpdateRequest) Script(script *Script) *BulkUpdateRequest {
r.script = script
@@ -132,7 +131,7 @@ func (r *BulkUpdateRequest) Script(script *Script) *BulkUpdateRequest {
// ScripedUpsert specifies if your script will run regardless of
// whether the document exists or not.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-update.html#_literal_scripted_upsert_literal
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html#_literal_scripted_upsert_literal
func (r *BulkUpdateRequest) ScriptedUpsert(upsert bool) *BulkUpdateRequest {
r.scriptedUpsert = &upsert
r.source = nil
@@ -155,7 +154,7 @@ func (r *BulkUpdateRequest) Version(version int64) *BulkUpdateRequest {
}
// VersionType can be "internal" (default), "external", "external_gte",
-// or "external_gt".
+// "external_gt", or "force".
func (r *BulkUpdateRequest) VersionType(versionType string) *BulkUpdateRequest {
r.versionType = versionType
r.source = nil
@@ -172,7 +171,7 @@ func (r *BulkUpdateRequest) Doc(doc interface{}) *BulkUpdateRequest {
// DocAsUpsert indicates whether the contents of Doc should be used as
// the Upsert value.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-update.html#_literal_doc_as_upsert_literal
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html#_literal_doc_as_upsert_literal
// for details.
func (r *BulkUpdateRequest) DocAsUpsert(docAsUpsert bool) *BulkUpdateRequest {
r.docAsUpsert = &docAsUpsert
@@ -218,7 +217,7 @@ func (r *BulkUpdateRequest) String() string {
// Source returns the on-wire representation of the update request,
// split into an action-and-meta-data line and an (optional) source line.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
// for details.
func (r *BulkUpdateRequest) Source() ([]string, error) {
// { "update" : { "_index" : "test", "_type" : "type1", "_id" : "1", ... } }
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_easyjson.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_easyjson.go
index d2c2cbfc7..1edd4c127 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_easyjson.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_easyjson.go
@@ -17,7 +17,7 @@ var (
_ easyjson.Marshaler
)
-func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUpdateRequestCommandOp) {
+func easyjson1ed00e60DecodeGopkgInOlivereElasticV5(in *jlexer.Lexer, out *bulkUpdateRequestCommandOp) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
@@ -36,15 +36,15 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUp
continue
}
switch key {
+ case "_id":
+ out.Id = string(in.String())
case "_index":
out.Index = string(in.String())
case "_type":
out.Type = string(in.String())
- case "_id":
- out.Id = string(in.String())
- case "parent":
+ case "_parent":
out.Parent = string(in.String())
- case "retry_on_conflict":
+ case "_retry_on_conflict":
if in.IsNull() {
in.Skip()
out.RetryOnConflict = nil
@@ -54,11 +54,11 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUp
}
*out.RetryOnConflict = int(in.Int())
}
- case "routing":
+ case "_routing":
out.Routing = string(in.String())
- case "version":
+ case "_version":
out.Version = int64(in.Int64())
- case "version_type":
+ case "_version_type":
out.VersionType = string(in.String())
default:
in.SkipRecursive()
@@ -70,42 +70,42 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUp
in.Consumed()
}
}
-func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkUpdateRequestCommandOp) {
+func easyjson1ed00e60EncodeGopkgInOlivereElasticV5(out *jwriter.Writer, in bulkUpdateRequestCommandOp) {
out.RawByte('{')
first := true
_ = first
- if in.Index != "" {
- const prefix string = ",\"_index\":"
+ if in.Id != "" {
+ const prefix string = ",\"_id\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Index))
+ out.String(string(in.Id))
}
- if in.Type != "" {
- const prefix string = ",\"_type\":"
+ if in.Index != "" {
+ const prefix string = ",\"_index\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Type))
+ out.String(string(in.Index))
}
- if in.Id != "" {
- const prefix string = ",\"_id\":"
+ if in.Type != "" {
+ const prefix string = ",\"_type\":"
if first {
first = false
out.RawString(prefix[1:])
} else {
out.RawString(prefix)
}
- out.String(string(in.Id))
+ out.String(string(in.Type))
}
if in.Parent != "" {
- const prefix string = ",\"parent\":"
+ const prefix string = ",\"_parent\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -115,7 +115,7 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU
out.String(string(in.Parent))
}
if in.RetryOnConflict != nil {
- const prefix string = ",\"retry_on_conflict\":"
+ const prefix string = ",\"_retry_on_conflict\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -125,7 +125,7 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU
out.Int(int(*in.RetryOnConflict))
}
if in.Routing != "" {
- const prefix string = ",\"routing\":"
+ const prefix string = ",\"_routing\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -135,7 +135,7 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU
out.String(string(in.Routing))
}
if in.Version != 0 {
- const prefix string = ",\"version\":"
+ const prefix string = ",\"_version\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -145,7 +145,7 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU
out.Int64(int64(in.Version))
}
if in.VersionType != "" {
- const prefix string = ",\"version_type\":"
+ const prefix string = ",\"_version_type\":"
if first {
first = false
out.RawString(prefix[1:])
@@ -160,27 +160,27 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU
// MarshalJSON supports json.Marshaler interface
func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson1ed00e60EncodeGithubComOlivereElastic(&w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkUpdateRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson1ed00e60EncodeGithubComOlivereElastic(w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV5(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson1ed00e60DecodeGithubComOlivereElastic(&r, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV5(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkUpdateRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson1ed00e60DecodeGithubComOlivereElastic(l, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV5(l, v)
}
-func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkUpdateRequestCommandData) {
+func easyjson1ed00e60DecodeGopkgInOlivereElasticV51(in *jlexer.Lexer, out *bulkUpdateRequestCommandData) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
@@ -227,6 +227,14 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkU
}
*out.DocAsUpsert = bool(in.Bool())
}
+ case "upsert":
+ if m, ok := out.Upsert.(easyjson.Unmarshaler); ok {
+ m.UnmarshalEasyJSON(in)
+ } else if m, ok := out.Upsert.(json.Unmarshaler); ok {
+ _ = m.UnmarshalJSON(in.Raw())
+ } else {
+ out.Upsert = in.Interface()
+ }
case "script":
if m, ok := out.Script.(easyjson.Unmarshaler); ok {
m.UnmarshalEasyJSON(in)
@@ -245,14 +253,6 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkU
}
*out.ScriptedUpsert = bool(in.Bool())
}
- case "upsert":
- if m, ok := out.Upsert.(easyjson.Unmarshaler); ok {
- m.UnmarshalEasyJSON(in)
- } else if m, ok := out.Upsert.(json.Unmarshaler); ok {
- _ = m.UnmarshalJSON(in.Raw())
- } else {
- out.Upsert = in.Interface()
- }
case "_source":
if in.IsNull() {
in.Skip()
@@ -273,7 +273,7 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkU
in.Consumed()
}
}
-func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkUpdateRequestCommandData) {
+func easyjson1ed00e60EncodeGopkgInOlivereElasticV51(out *jwriter.Writer, in bulkUpdateRequestCommandData) {
out.RawByte('{')
first := true
_ = first
@@ -313,6 +313,22 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk
}
out.Bool(bool(*in.DocAsUpsert))
}
+ if in.Upsert != nil {
+ const prefix string = ",\"upsert\":"
+ if first {
+ first = false
+ out.RawString(prefix[1:])
+ } else {
+ out.RawString(prefix)
+ }
+ if m, ok := in.Upsert.(easyjson.Marshaler); ok {
+ m.MarshalEasyJSON(out)
+ } else if m, ok := in.Upsert.(json.Marshaler); ok {
+ out.Raw(m.MarshalJSON())
+ } else {
+ out.Raw(json.Marshal(in.Upsert))
+ }
+ }
if in.Script != nil {
const prefix string = ",\"script\":"
if first {
@@ -339,22 +355,6 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk
}
out.Bool(bool(*in.ScriptedUpsert))
}
- if in.Upsert != nil {
- const prefix string = ",\"upsert\":"
- if first {
- first = false
- out.RawString(prefix[1:])
- } else {
- out.RawString(prefix)
- }
- if m, ok := in.Upsert.(easyjson.Marshaler); ok {
- m.MarshalEasyJSON(out)
- } else if m, ok := in.Upsert.(json.Marshaler); ok {
- out.Raw(m.MarshalJSON())
- } else {
- out.Raw(json.Marshal(in.Upsert))
- }
- }
if in.Source != nil {
const prefix string = ",\"_source\":"
if first {
@@ -371,27 +371,27 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk
// MarshalJSON supports json.Marshaler interface
func (v bulkUpdateRequestCommandData) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson1ed00e60EncodeGithubComOlivereElastic1(&w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV51(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkUpdateRequestCommandData) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson1ed00e60EncodeGithubComOlivereElastic1(w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV51(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson1ed00e60DecodeGithubComOlivereElastic1(&r, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV51(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkUpdateRequestCommandData) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson1ed00e60DecodeGithubComOlivereElastic1(l, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV51(l, v)
}
-func easyjson1ed00e60DecodeGithubComOlivereElastic2(in *jlexer.Lexer, out *bulkUpdateRequestCommand) {
+func easyjson1ed00e60DecodeGopkgInOlivereElasticV52(in *jlexer.Lexer, out *bulkUpdateRequestCommand) {
isTopLevel := in.IsStart()
if in.IsNull() {
in.Skip()
@@ -416,7 +416,7 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic2(in *jlexer.Lexer, out *bulkU
in.Consumed()
}
}
-func easyjson1ed00e60EncodeGithubComOlivereElastic2(out *jwriter.Writer, in bulkUpdateRequestCommand) {
+func easyjson1ed00e60EncodeGopkgInOlivereElasticV52(out *jwriter.Writer, in bulkUpdateRequestCommand) {
if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 {
out.RawString(`null`)
} else {
@@ -439,23 +439,23 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic2(out *jwriter.Writer, in bulk
// MarshalJSON supports json.Marshaler interface
func (v bulkUpdateRequestCommand) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
- easyjson1ed00e60EncodeGithubComOlivereElastic2(&w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV52(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v bulkUpdateRequestCommand) MarshalEasyJSON(w *jwriter.Writer) {
- easyjson1ed00e60EncodeGithubComOlivereElastic2(w, v)
+ easyjson1ed00e60EncodeGopkgInOlivereElasticV52(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
- easyjson1ed00e60DecodeGithubComOlivereElastic2(&r, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV52(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *bulkUpdateRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) {
- easyjson1ed00e60DecodeGithubComOlivereElastic2(l, v)
+ easyjson1ed00e60DecodeGopkgInOlivereElasticV52(l, v)
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_test.go b/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_test.go
deleted file mode 100644
index 53e73bd40..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/bulk_update_request_test.go
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestBulkUpdateRequestSerialization(t *testing.T) {
- tests := []struct {
- Request BulkableRequest
- Expected []string
- }{
- // #0
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"1"}}`,
- `{"doc":{"counter":42}}`,
- },
- },
- // #1
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").
- Routing("123").
- RetryOnConflict(3).
- DocAsUpsert(true).
- Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"1","retry_on_conflict":3,"routing":"123"}}`,
- `{"doc":{"counter":42},"doc_as_upsert":true}`,
- },
- },
- // #2
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").
- RetryOnConflict(3).
- Script(NewScript(`ctx._source.retweets += param1`).Lang("javascript").Param("param1", 42)).
- Upsert(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"1","retry_on_conflict":3}}`,
- `{"script":{"lang":"javascript","params":{"param1":42},"source":"ctx._source.retweets += param1"},"upsert":{"counter":42}}`,
- },
- },
- // #3
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").DetectNoop(true).Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"1"}}`,
- `{"detect_noop":true,"doc":{"counter":42}}`,
- },
- },
- // #4
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").
- RetryOnConflict(3).
- ScriptedUpsert(true).
- Script(NewScript(`ctx._source.retweets += param1`).Lang("javascript").Param("param1", 42)).
- Upsert(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"1","retry_on_conflict":3}}`,
- `{"script":{"lang":"javascript","params":{"param1":42},"source":"ctx._source.retweets += param1"},"scripted_upsert":true,"upsert":{"counter":42}}`,
- },
- },
- // #5
- {
- Request: NewBulkUpdateRequest().Index("index1").Type("doc").Id("4").ReturnSource(true).Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }),
- Expected: []string{
- `{"update":{"_index":"index1","_type":"doc","_id":"4"}}`,
- `{"doc":{"counter":42},"_source":true}`,
- },
- },
- }
-
- for i, test := range tests {
- lines, err := test.Request.Source()
- if err != nil {
- t.Fatalf("#%d: expected no error, got: %v", i, err)
- }
- if lines == nil {
- t.Fatalf("#%d: expected lines, got nil", i)
- }
- if len(lines) != len(test.Expected) {
- t.Fatalf("#%d: expected %d lines, got %d", i, len(test.Expected), len(lines))
- }
- for j, line := range lines {
- if line != test.Expected[j] {
- t.Errorf("#%d: expected line #%d to be\n%s\nbut got:\n%s", i, j, test.Expected[j], line)
- }
- }
- }
-}
-
-var bulkUpdateRequestSerializationResult string
-
-func BenchmarkBulkUpdateRequestSerialization(b *testing.B) {
- b.Run("stdlib", func(b *testing.B) {
- r := NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- })
- benchmarkBulkUpdateRequestSerialization(b, r.UseEasyJSON(false))
- })
- b.Run("easyjson", func(b *testing.B) {
- r := NewBulkUpdateRequest().Index("index1").Type("doc").Id("1").Doc(struct {
- Counter int64 `json:"counter"`
- }{
- Counter: 42,
- }).UseEasyJSON(false)
- benchmarkBulkUpdateRequestSerialization(b, r.UseEasyJSON(true))
- })
-}
-
-func benchmarkBulkUpdateRequestSerialization(b *testing.B, r *BulkUpdateRequest) {
- var s string
- for n := 0; n < b.N; n++ {
- s = r.String()
- r.source = nil // Don't let caching spoil the benchmark
- }
- bulkUpdateRequestSerializationResult = s // ensure the compiler doesn't optimize
- b.ReportAllocs()
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/canonicalize_test.go b/vendor/gopkg.in/olivere/elastic.v5/canonicalize_test.go
deleted file mode 100644
index 86b62d498..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/canonicalize_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestCanonicalize(t *testing.T) {
- tests := []struct {
- Input []string
- Output []string
- }{
- // #0
- {
- Input: []string{"http://127.0.0.1/"},
- Output: []string{"http://127.0.0.1"},
- },
- // #1
- {
- Input: []string{"http://127.0.0.1:9200/", "gopher://golang.org/", "http://127.0.0.1:9201"},
- Output: []string{"http://127.0.0.1:9200", "http://127.0.0.1:9201"},
- },
- // #2
- {
- Input: []string{"http://user:secret@127.0.0.1/path?query=1#fragment"},
- Output: []string{"http://user:secret@127.0.0.1/path"},
- },
- // #3
- {
- Input: []string{"https://somewhere.on.mars:9999/path?query=1#fragment"},
- Output: []string{"https://somewhere.on.mars:9999/path"},
- },
- // #4
- {
- Input: []string{"https://prod1:9999/one?query=1#fragment", "https://prod2:9998/two?query=1#fragment"},
- Output: []string{"https://prod1:9999/one", "https://prod2:9998/two"},
- },
- // #5
- {
- Input: []string{"http://127.0.0.1/one/"},
- Output: []string{"http://127.0.0.1/one"},
- },
- // #6
- {
- Input: []string{"http://127.0.0.1/one///"},
- Output: []string{"http://127.0.0.1/one"},
- },
- // #7: Invalid URL
- {
- Input: []string{"127.0.0.1/"},
- Output: []string{},
- },
- // #8: Invalid URL
- {
- Input: []string{"127.0.0.1:9200"},
- Output: []string{},
- },
- }
-
- for i, test := range tests {
- got := canonicalize(test.Input...)
- if want, have := len(test.Output), len(got); want != have {
- t.Fatalf("#%d: expected %d elements; got: %d", i, want, have)
- }
- for i := 0; i < len(got); i++ {
- if want, have := test.Output[i], got[i]; want != have {
- t.Errorf("#%d: expected %q; got: %q", i, want, have)
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/clear_scroll.go b/vendor/gopkg.in/olivere/elastic.v5/clear_scroll.go
index 4f449504c..83e592875 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/clear_scroll.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/clear_scroll.go
@@ -12,7 +12,7 @@ import (
// ClearScrollService clears one or more scroll contexts by their ids.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html#_clear_scroll_api
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#_clear_scroll_api
// for details.
type ClearScrollService struct {
client *Client
@@ -49,7 +49,7 @@ func (s *ClearScrollService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
return path, params, nil
}
@@ -85,12 +85,7 @@ func (s *ClearScrollService) Do(ctx context.Context) (*ClearScrollResponse, erro
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/clear_scroll_test.go b/vendor/gopkg.in/olivere/elastic.v5/clear_scroll_test.go
deleted file mode 100644
index 4037d3cd6..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/clear_scroll_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- _ "net/http"
- "testing"
-)
-
-func TestClearScroll(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- // client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- res, err := client.Scroll(testIndexName).Size(1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected results != nil; got nil")
- }
- if res.ScrollId == "" {
- t.Fatalf("expected scrollId in results; got %q", res.ScrollId)
- }
-
- // Search should succeed
- _, err = client.Scroll(testIndexName).Size(1).ScrollId(res.ScrollId).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Clear scroll id
- clearScrollRes, err := client.ClearScroll().ScrollId(res.ScrollId).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if clearScrollRes == nil {
- t.Fatal("expected results != nil; got nil")
- }
-
- // Search result should fail
- _, err = client.Scroll(testIndexName).Size(1).ScrollId(res.ScrollId).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected scroll to fail")
- }
-}
-
-func TestClearScrollValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No scroll id -> fail with error
- res, err := NewClearScrollService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected ClearScroll to fail without scroll ids")
- }
- if res != nil {
- t.Fatalf("expected result to be nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/client.go b/vendor/gopkg.in/olivere/elastic.v5/client.go
index 165a30526..e709b0bf4 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/client.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/client.go
@@ -21,12 +21,12 @@ import (
"github.com/pkg/errors"
- "github.com/olivere/elastic/config"
+ "gopkg.in/olivere/elastic.v5/config"
)
const (
// Version is the current version of Elastic.
- Version = "6.1.7"
+ Version = "5.0.66"
// DefaultURL is the default endpoint of Elasticsearch on the local machine.
// It is used e.g. when initializing a new Client without a specific URL.
@@ -76,6 +76,9 @@ const (
// a GET request with a body.
DefaultSendGetBodyAs = "GET"
+ // DefaultGzipEnabled specifies if gzip compression is enabled by default.
+ DefaultGzipEnabled = false
+
// off is used to disable timeouts.
off = -1 * time.Second
)
@@ -132,6 +135,7 @@ type Client struct {
basicAuthPassword string // password for HTTP Basic Auth
sendGetBodyAs string // override for when sending a GET with a body
requiredPlugins []string // list of required plugins
+ gzipEnabled bool // gzip compression enabled or disabled (default)
retrier Retrier // strategy for retries
}
@@ -154,7 +158,7 @@ type Client struct {
//
// If the sniffer is enabled (the default), the new client then sniffes
// the cluster via the Nodes Info API
-// (see https://www.elastic.co/guide/en/elasticsearch/reference/6.0/cluster-nodes-info.html#cluster-nodes-info).
+// (see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-nodes-info.html#cluster-nodes-info).
// It uses the URLs specified by the caller. The caller is responsible
// to only pass a list of URLs of nodes that belong to the same cluster.
// This sniffing process is run on startup and periodically.
@@ -205,6 +209,7 @@ func NewClient(options ...ClientOptionFunc) (*Client, error) {
snifferCallback: nopSnifferCallback,
snifferStop: make(chan bool),
sendGetBodyAs: DefaultSendGetBodyAs,
+ gzipEnabled: DefaultGzipEnabled,
retrier: noRetries, // no retries by default
}
@@ -362,6 +367,7 @@ func NewSimpleClient(options ...ClientOptionFunc) (*Client, error) {
snifferCallback: nopSnifferCallback,
snifferStop: make(chan bool),
sendGetBodyAs: DefaultSendGetBodyAs,
+ gzipEnabled: DefaultGzipEnabled,
retrier: noRetries, // no retries by default
}
@@ -590,6 +596,14 @@ func SetMaxRetries(maxRetries int) ClientOptionFunc {
}
}
+// SetGzip enables or disables gzip compression (disabled by default).
+func SetGzip(enabled bool) ClientOptionFunc {
+ return func(c *Client) error {
+ c.gzipEnabled = enabled
+ return nil
+ }
+}
+
// SetDecoder sets the Decoder to use when decoding data from Elasticsearch.
// DefaultDecoder is used by default.
func SetDecoder(decoder Decoder) ClientOptionFunc {
@@ -1075,11 +1089,6 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error {
var lastErr error
start := time.Now()
for {
- // Make a copy of the HTTP client provided via options to respect
- // settings like Basic Auth or a user-specified http.Transport.
- cl := new(http.Client)
- *cl = *c.c
- cl.Timeout = timeout
for _, url := range urls {
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
@@ -1088,7 +1097,10 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error {
if basicAuth {
req.SetBasicAuth(basicAuthUsername, basicAuthPassword)
}
- res, err := cl.Do(req)
+ ctx, cancel := context.WithTimeout(req.Context(), timeout)
+ defer cancel()
+ req = req.WithContext(ctx)
+ res, err := c.c.Do(req)
if err == nil && res != nil && res.StatusCode >= 200 && res.StatusCode < 300 {
return nil
} else if err != nil {
@@ -1096,7 +1108,7 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error {
}
}
time.Sleep(1 * time.Second)
- if time.Now().Sub(start) > timeout {
+ if time.Since(start) > timeout {
break
}
}
@@ -1173,12 +1185,38 @@ type PerformRequestOptions struct {
}
// PerformRequest does a HTTP request to Elasticsearch.
+// See PerformRequestWithContentType for details.
+func (c *Client) PerformRequest(ctx context.Context, method, path string, params url.Values, body interface{}, ignoreErrors ...int) (*Response, error) {
+ return c.PerformRequestWithOptions(ctx, PerformRequestOptions{
+ Method: method,
+ Path: path,
+ Params: params,
+ Body: body,
+ ContentType: "application/json",
+ IgnoreErrors: ignoreErrors,
+ })
+}
+
+// PerformRequestWithContentType executes a HTTP request with a specific content type.
// It returns a response (which might be nil) and an error on failure.
//
// Optionally, a list of HTTP error codes to ignore can be passed.
// This is necessary for services that expect e.g. HTTP status 404 as a
// valid outcome (Exists, IndicesExists, IndicesTypeExists).
-func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) (*Response, error) {
+func (c *Client) PerformRequestWithContentType(ctx context.Context, method, path string, params url.Values, body interface{}, contentType string, ignoreErrors ...int) (*Response, error) {
+ return c.PerformRequestWithOptions(ctx, PerformRequestOptions{
+ Method: method,
+ Path: path,
+ Params: params,
+ Body: body,
+ ContentType: contentType,
+ IgnoreErrors: ignoreErrors,
+ })
+}
+
+// PerformRequestWithOptions executes a HTTP request with the specified options.
+// It returns a response (which might be nil) and an error on failure.
+func (c *Client) PerformRequestWithOptions(ctx context.Context, opt PerformRequestOptions) (*Response, error) {
start := time.Now().UTC()
c.mu.RLock()
@@ -1187,6 +1225,7 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions)
basicAuthUsername := c.basicAuthUsername
basicAuthPassword := c.basicAuthPassword
sendGetBodyAs := c.sendGetBodyAs
+ gzipEnabled := c.gzipEnabled
retrier := c.retrier
if opt.Retrier != nil {
retrier = opt.Retrier
@@ -1250,7 +1289,7 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions)
// Set body
if opt.Body != nil {
- err = req.SetBody(opt.Body)
+ err = req.SetBody(opt.Body, gzipEnabled)
if err != nil {
c.errorf("elastic: couldn't set body %+v for request: %v", opt.Body, err)
return nil, err
@@ -1297,11 +1336,6 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions)
// Tracing
c.dumpResponse(res)
- // Log deprecation warnings as errors
- if s := res.Header.Get("Warning"); s != "" {
- c.errorf(s)
- }
-
// Check for errors
if err := checkResponse((*http.Request)(req), res, opt.IgnoreErrors...); err != nil {
// No retry if request succeeded
@@ -1385,7 +1419,7 @@ func (c *Client) BulkProcessor() *BulkProcessorService {
// Reindex copies data from a source index into a destination index.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-reindex.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-reindex.html
// for details on the Reindex API.
func (c *Client) Reindex() *ReindexService {
return NewReindexService(c)
@@ -1412,6 +1446,11 @@ func (c *Client) Search(indices ...string) *SearchService {
return NewSearchService(c).Index(indices...)
}
+// Suggest returns a service to return suggestions.
+func (c *Client) Suggest(indices ...string) *SuggestService {
+ return NewSuggestService(c).Index(indices...)
+}
+
// MultiSearch is the entry point for multi searches.
func (c *Client) MultiSearch() *MultiSearchService {
return NewMultiSearchService(c)
@@ -1428,15 +1467,28 @@ func (c *Client) Explain(index, typ, id string) *ExplainService {
}
// TODO Search Template
-// TODO Search Shards API
// TODO Search Exists API
-// TODO Validate API
+
+// Validate allows a user to validate a potentially expensive query without executing it.
+func (c *Client) Validate(indices ...string) *ValidateService {
+ return NewValidateService(c).Index(indices...)
+}
+
+// SearchShards returns statistical information about nodes and shards.
+func (c *Client) SearchShards(indices ...string) *SearchShardsService {
+ return NewSearchShardsService(c).Index(indices...)
+}
// FieldCaps returns statistical information about fields in indices.
func (c *Client) FieldCaps(indices ...string) *FieldCapsService {
return NewFieldCapsService(c).Index(indices...)
}
+// FieldStats returns statistical information about fields in indices.
+func (c *Client) FieldStats(indices ...string) *FieldStatsService {
+ return NewFieldStatsService(c).Index(indices...)
+}
+
// Exists checks if a document exists.
func (c *Client) Exists() *ExistsService {
return NewExistsService(c)
@@ -1556,6 +1608,24 @@ func (c *Client) Aliases() *AliasesService {
return NewAliasesService(c)
}
+// GetTemplate gets a search template.
+// Use IndexXXXTemplate funcs to manage index templates.
+func (c *Client) GetTemplate() *GetTemplateService {
+ return NewGetTemplateService(c)
+}
+
+// PutTemplate creates or updates a search template.
+// Use IndexXXXTemplate funcs to manage index templates.
+func (c *Client) PutTemplate() *PutTemplateService {
+ return NewPutTemplateService(c)
+}
+
+// DeleteTemplate deletes a search template.
+// Use IndexXXXTemplate funcs to manage index templates.
+func (c *Client) DeleteTemplate() *DeleteTemplateService {
+ return NewDeleteTemplateService(c)
+}
+
// IndexGetTemplate gets an index template.
// Use XXXTemplate funcs to manage search templates.
func (c *Client) IndexGetTemplate(names ...string) *IndicesGetTemplateService {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/client_test.go b/vendor/gopkg.in/olivere/elastic.v5/client_test.go
deleted file mode 100644
index 4d0440ee0..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/client_test.go
+++ /dev/null
@@ -1,1319 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "log"
- "net"
- "net/http"
- "reflect"
- "regexp"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/fortytw2/leaktest"
-)
-
-func findConn(s string, slice ...*conn) (int, bool) {
- for i, t := range slice {
- if s == t.URL() {
- return i, true
- }
- }
- return -1, false
-}
-
-// -- NewClient --
-
-func TestClientDefaults(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- if client.healthcheckEnabled != true {
- t.Errorf("expected health checks to be enabled, got: %v", client.healthcheckEnabled)
- }
- if client.healthcheckTimeoutStartup != DefaultHealthcheckTimeoutStartup {
- t.Errorf("expected health checks timeout on startup = %v, got: %v", DefaultHealthcheckTimeoutStartup, client.healthcheckTimeoutStartup)
- }
- if client.healthcheckTimeout != DefaultHealthcheckTimeout {
- t.Errorf("expected health checks timeout = %v, got: %v", DefaultHealthcheckTimeout, client.healthcheckTimeout)
- }
- if client.healthcheckInterval != DefaultHealthcheckInterval {
- t.Errorf("expected health checks interval = %v, got: %v", DefaultHealthcheckInterval, client.healthcheckInterval)
- }
- if client.snifferEnabled != true {
- t.Errorf("expected sniffing to be enabled, got: %v", client.snifferEnabled)
- }
- if client.snifferTimeoutStartup != DefaultSnifferTimeoutStartup {
- t.Errorf("expected sniffer timeout on startup = %v, got: %v", DefaultSnifferTimeoutStartup, client.snifferTimeoutStartup)
- }
- if client.snifferTimeout != DefaultSnifferTimeout {
- t.Errorf("expected sniffer timeout = %v, got: %v", DefaultSnifferTimeout, client.snifferTimeout)
- }
- if client.snifferInterval != DefaultSnifferInterval {
- t.Errorf("expected sniffer interval = %v, got: %v", DefaultSnifferInterval, client.snifferInterval)
- }
- if client.basicAuth != false {
- t.Errorf("expected no basic auth; got: %v", client.basicAuth)
- }
- if client.basicAuthUsername != "" {
- t.Errorf("expected no basic auth username; got: %q", client.basicAuthUsername)
- }
- if client.basicAuthPassword != "" {
- t.Errorf("expected no basic auth password; got: %q", client.basicAuthUsername)
- }
- if client.sendGetBodyAs != "GET" {
- t.Errorf("expected sendGetBodyAs to be GET; got: %q", client.sendGetBodyAs)
- }
-}
-
-func TestClientWithoutURL(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- // Two things should happen here:
- // 1. The client starts sniffing the cluster on DefaultURL
- // 2. The sniffing process should find (at least) one node in the cluster, i.e. the DefaultURL
- if len(client.conns) == 0 {
- t.Fatalf("expected at least 1 node in the cluster, got: %d (%v)", len(client.conns), client.conns)
- }
- if !isTravis() {
- if _, found := findConn(DefaultURL, client.conns...); !found {
- t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
- }
- }
-}
-
-func TestClientWithSingleURL(t *testing.T) {
- client, err := NewClient(SetURL("http://127.0.0.1:9200"))
- if err != nil {
- t.Fatal(err)
- }
- // Two things should happen here:
- // 1. The client starts sniffing the cluster on DefaultURL
- // 2. The sniffing process should find (at least) one node in the cluster, i.e. the DefaultURL
- if len(client.conns) == 0 {
- t.Fatalf("expected at least 1 node in the cluster, got: %d (%v)", len(client.conns), client.conns)
- }
- if !isTravis() {
- if _, found := findConn(DefaultURL, client.conns...); !found {
- t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
- }
- }
-}
-
-func TestClientWithMultipleURLs(t *testing.T) {
- client, err := NewClient(SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
- // The client should sniff both URLs, but only 127.0.0.1:9200 should return nodes.
- if len(client.conns) != 1 {
- t.Fatalf("expected exactly 1 node in the local cluster, got: %d (%v)", len(client.conns), client.conns)
- }
- if !isTravis() {
- if client.conns[0].URL() != DefaultURL {
- t.Errorf("expected to find node with default URL of %s in %v", DefaultURL, client.conns)
- }
- }
-}
-
-func TestClientWithBasicAuth(t *testing.T) {
- client, err := NewClient(SetBasicAuth("user", "secret"))
- if err != nil {
- t.Fatal(err)
- }
- if client.basicAuth != true {
- t.Errorf("expected basic auth; got: %v", client.basicAuth)
- }
- if got, want := client.basicAuthUsername, "user"; got != want {
- t.Errorf("expected basic auth username %q; got: %q", want, got)
- }
- if got, want := client.basicAuthPassword, "secret"; got != want {
- t.Errorf("expected basic auth password %q; got: %q", want, got)
- }
-}
-
-func TestClientWithBasicAuthInUserInfo(t *testing.T) {
- client, err := NewClient(SetURL("http://user1:secret1@localhost:9200", "http://user2:secret2@localhost:9200"))
- if err != nil {
- t.Fatal(err)
- }
- if client.basicAuth != true {
- t.Errorf("expected basic auth; got: %v", client.basicAuth)
- }
- if got, want := client.basicAuthUsername, "user1"; got != want {
- t.Errorf("expected basic auth username %q; got: %q", want, got)
- }
- if got, want := client.basicAuthPassword, "secret1"; got != want {
- t.Errorf("expected basic auth password %q; got: %q", want, got)
- }
-}
-
-func TestClientSniffSuccess(t *testing.T) {
- client, err := NewClient(SetURL("http://127.0.0.1:19200", "http://127.0.0.1:9200"))
- if err != nil {
- t.Fatal(err)
- }
- // The client should sniff both URLs, but only 127.0.0.1:9200 should return nodes.
- if len(client.conns) != 1 {
- t.Fatalf("expected exactly 1 node in the local cluster, got: %d (%v)", len(client.conns), client.conns)
- }
-}
-
-func TestClientSniffFailure(t *testing.T) {
- _, err := NewClient(SetURL("http://127.0.0.1:19200", "http://127.0.0.1:19201"))
- if err == nil {
- t.Fatalf("expected cluster to fail with no nodes found")
- }
-}
-
-func TestClientSnifferCallback(t *testing.T) {
- var calls int
- cb := func(node *NodesInfoNode) bool {
- calls++
- return false
- }
- _, err := NewClient(
- SetURL("http://127.0.0.1:19200", "http://127.0.0.1:9200"),
- SetSnifferCallback(cb))
- if err == nil {
- t.Fatalf("expected cluster to fail with no nodes found")
- }
- if calls != 1 {
- t.Fatalf("expected 1 call to the sniffer callback, got %d", calls)
- }
-}
-
-func TestClientSniffDisabled(t *testing.T) {
- client, err := NewClient(SetSniff(false), SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
- // The client should not sniff, so it should have two connections.
- if len(client.conns) != 2 {
- t.Fatalf("expected 2 nodes, got: %d (%v)", len(client.conns), client.conns)
- }
- // Make two requests, so that both connections are being used
- for i := 0; i < len(client.conns); i++ {
- client.Flush().Do(context.TODO())
- }
- // The first connection (127.0.0.1:9200) should now be okay.
- if i, found := findConn("http://127.0.0.1:9200", client.conns...); !found {
- t.Fatalf("expected connection to %q to be found", "http://127.0.0.1:9200")
- } else {
- if conn := client.conns[i]; conn.IsDead() {
- t.Fatal("expected connection to be alive, but it is dead")
- }
- }
- // The second connection (127.0.0.1:9201) should now be marked as dead.
- if i, found := findConn("http://127.0.0.1:9201", client.conns...); !found {
- t.Fatalf("expected connection to %q to be found", "http://127.0.0.1:9201")
- } else {
- if conn := client.conns[i]; !conn.IsDead() {
- t.Fatal("expected connection to be dead, but it is alive")
- }
- }
-}
-
-func TestClientWillMarkConnectionsAsAliveWhenAllAreDead(t *testing.T) {
- client, err := NewClient(SetURL("http://127.0.0.1:9201"),
- SetSniff(false), SetHealthcheck(false), SetMaxRetries(0))
- if err != nil {
- t.Fatal(err)
- }
- // We should have a connection.
- if len(client.conns) != 1 {
- t.Fatalf("expected 1 node, got: %d (%v)", len(client.conns), client.conns)
- }
-
- // Make a request, so that the connections is marked as dead.
- client.Flush().Do(context.TODO())
-
- // The connection should now be marked as dead.
- if i, found := findConn("http://127.0.0.1:9201", client.conns...); !found {
- t.Fatalf("expected connection to %q to be found", "http://127.0.0.1:9201")
- } else {
- if conn := client.conns[i]; !conn.IsDead() {
- t.Fatalf("expected connection to be dead, got: %v", conn)
- }
- }
-
- // Now send another request and the connection should be marked as alive again.
- client.Flush().Do(context.TODO())
-
- if i, found := findConn("http://127.0.0.1:9201", client.conns...); !found {
- t.Fatalf("expected connection to %q to be found", "http://127.0.0.1:9201")
- } else {
- if conn := client.conns[i]; conn.IsDead() {
- t.Fatalf("expected connection to be alive, got: %v", conn)
- }
- }
-}
-
-func TestClientWithRequiredPlugins(t *testing.T) {
- _, err := NewClient(SetRequiredPlugins("no-such-plugin"))
- if err == nil {
- t.Fatal("expected error when creating client")
- }
- if got, want := err.Error(), "elastic: plugin no-such-plugin not found"; got != want {
- t.Fatalf("expected error %q; got: %q", want, got)
- }
-}
-
-func TestClientHealthcheckStartupTimeout(t *testing.T) {
- start := time.Now()
- _, err := NewClient(SetURL("http://localhost:9299"), SetHealthcheckTimeoutStartup(5*time.Second))
- duration := time.Now().Sub(start)
- if !IsConnErr(err) {
- t.Fatal(err)
- }
- if !strings.Contains(err.Error(), "connection refused") {
- t.Fatalf("expected error to contain %q, have %q", "connection refused", err.Error())
- }
- if duration < 5*time.Second {
- t.Fatalf("expected a timeout in more than 5 seconds; got: %v", duration)
- }
-}
-
-func TestClientHealthcheckTimeoutLeak(t *testing.T) {
- // This test test checks if healthcheck requests are canceled
- // after timeout.
- // It contains couple of hacks which won't be needed once we
- // stop supporting Go1.7.
- // On Go1.7 it uses server side effects to monitor if connection
- // was closed,
- // and on Go 1.8+ we're additionally honestly monitoring routine
- // leaks via leaktest.
- mux := http.NewServeMux()
-
- var reqDoneMu sync.Mutex
- var reqDone bool
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- cn, ok := w.(http.CloseNotifier)
- if !ok {
- t.Fatalf("Writer is not CloseNotifier, but %v", reflect.TypeOf(w).Name())
- }
- <-cn.CloseNotify()
- reqDoneMu.Lock()
- reqDone = true
- reqDoneMu.Unlock()
- })
-
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("Couldn't setup listener: %v", err)
- }
- addr := lis.Addr().String()
-
- srv := &http.Server{
- Handler: mux,
- }
- go srv.Serve(lis)
-
- cli := &Client{
- c: &http.Client{},
- conns: []*conn{
- &conn{
- url: "http://" + addr + "/",
- },
- },
- }
-
- type closer interface {
- Shutdown(context.Context) error
- }
-
- // pre-Go1.8 Server can't Shutdown
- cl, isServerCloseable := (interface{}(srv)).(closer)
-
- // Since Go1.7 can't Shutdown() - there will be leak from server
- // Monitor leaks on Go 1.8+
- if isServerCloseable {
- defer leaktest.CheckTimeout(t, time.Second*10)()
- }
-
- cli.healthcheck(time.Millisecond*500, true)
-
- if isServerCloseable {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
- defer cancel()
- cl.Shutdown(ctx)
- }
-
- <-time.After(time.Second)
- reqDoneMu.Lock()
- if !reqDone {
- reqDoneMu.Unlock()
- t.Fatal("Request wasn't canceled or stopped")
- }
- reqDoneMu.Unlock()
-}
-
-// -- NewSimpleClient --
-
-func TestSimpleClientDefaults(t *testing.T) {
- client, err := NewSimpleClient()
- if err != nil {
- t.Fatal(err)
- }
- if client.healthcheckEnabled != false {
- t.Errorf("expected health checks to be disabled, got: %v", client.healthcheckEnabled)
- }
- if client.healthcheckTimeoutStartup != off {
- t.Errorf("expected health checks timeout on startup = %v, got: %v", off, client.healthcheckTimeoutStartup)
- }
- if client.healthcheckTimeout != off {
- t.Errorf("expected health checks timeout = %v, got: %v", off, client.healthcheckTimeout)
- }
- if client.healthcheckInterval != off {
- t.Errorf("expected health checks interval = %v, got: %v", off, client.healthcheckInterval)
- }
- if client.snifferEnabled != false {
- t.Errorf("expected sniffing to be disabled, got: %v", client.snifferEnabled)
- }
- if client.snifferTimeoutStartup != off {
- t.Errorf("expected sniffer timeout on startup = %v, got: %v", off, client.snifferTimeoutStartup)
- }
- if client.snifferTimeout != off {
- t.Errorf("expected sniffer timeout = %v, got: %v", off, client.snifferTimeout)
- }
- if client.snifferInterval != off {
- t.Errorf("expected sniffer interval = %v, got: %v", off, client.snifferInterval)
- }
- if client.basicAuth != false {
- t.Errorf("expected no basic auth; got: %v", client.basicAuth)
- }
- if client.basicAuthUsername != "" {
- t.Errorf("expected no basic auth username; got: %q", client.basicAuthUsername)
- }
- if client.basicAuthPassword != "" {
- t.Errorf("expected no basic auth password; got: %q", client.basicAuthUsername)
- }
- if client.sendGetBodyAs != "GET" {
- t.Errorf("expected sendGetBodyAs to be GET; got: %q", client.sendGetBodyAs)
- }
-}
-
-// -- Start and stop --
-
-func TestClientStartAndStop(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
-
- running := client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-
- // Stop
- client.Stop()
- running = client.IsRunning()
- if running {
- t.Fatalf("expected background processes to be stopped; got: %v", running)
- }
-
- // Stop again => no-op
- client.Stop()
- running = client.IsRunning()
- if running {
- t.Fatalf("expected background processes to be stopped; got: %v", running)
- }
-
- // Start
- client.Start()
- running = client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-
- // Start again => no-op
- client.Start()
- running = client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-}
-
-func TestClientStartAndStopWithSnifferAndHealthchecksDisabled(t *testing.T) {
- client, err := NewClient(SetSniff(false), SetHealthcheck(false))
- if err != nil {
- t.Fatal(err)
- }
-
- running := client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-
- // Stop
- client.Stop()
- running = client.IsRunning()
- if running {
- t.Fatalf("expected background processes to be stopped; got: %v", running)
- }
-
- // Stop again => no-op
- client.Stop()
- running = client.IsRunning()
- if running {
- t.Fatalf("expected background processes to be stopped; got: %v", running)
- }
-
- // Start
- client.Start()
- running = client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-
- // Start again => no-op
- client.Start()
- running = client.IsRunning()
- if !running {
- t.Fatalf("expected background processes to run; got: %v", running)
- }
-}
-
-// -- Sniffing --
-
-func TestClientSniffNode(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
-
- ch := make(chan []*conn)
- go func() { ch <- client.sniffNode(context.Background(), DefaultURL) }()
-
- select {
- case nodes := <-ch:
- if len(nodes) != 1 {
- t.Fatalf("expected %d nodes; got: %d", 1, len(nodes))
- }
- pattern := `http:\/\/[\d\.]+:9200`
- matched, err := regexp.MatchString(pattern, nodes[0].URL())
- if err != nil {
- t.Fatal(err)
- }
- if !matched {
- t.Fatalf("expected node URL pattern %q; got: %q", pattern, nodes[0].URL())
- }
- case <-time.After(2 * time.Second):
- t.Fatal("expected no timeout in sniff node")
- break
- }
-}
-
-func TestClientSniffOnDefaultURL(t *testing.T) {
- client, _ := NewClient()
- if client == nil {
- t.Fatal("no client returned")
- }
-
- ch := make(chan error, 1)
- go func() {
- ch <- client.sniff(DefaultSnifferTimeoutStartup)
- }()
-
- select {
- case err := <-ch:
- if err != nil {
- t.Fatalf("expected sniff to succeed; got: %v", err)
- }
- if len(client.conns) != 1 {
- t.Fatalf("expected %d nodes; got: %d", 1, len(client.conns))
- }
- pattern := `http:\/\/[\d\.]+:9200`
- matched, err := regexp.MatchString(pattern, client.conns[0].URL())
- if err != nil {
- t.Fatal(err)
- }
- if !matched {
- t.Fatalf("expected node URL pattern %q; got: %q", pattern, client.conns[0].URL())
- }
- case <-time.After(2 * time.Second):
- t.Fatal("expected no timeout in sniff")
- break
- }
-}
-
-func TestClientSniffTimeoutLeak(t *testing.T) {
- // This test test checks if sniff requests are canceled
- // after timeout.
- // It contains couple of hacks which won't be needed once we
- // stop supporting Go1.7.
- // On Go1.7 it uses server side effects to monitor if connection
- // was closed,
- // and on Go 1.8+ we're additionally honestly monitoring routine
- // leaks via leaktest.
- mux := http.NewServeMux()
-
- var reqDoneMu sync.Mutex
- var reqDone bool
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- cn, ok := w.(http.CloseNotifier)
- if !ok {
- t.Fatalf("Writer is not CloseNotifier, but %v", reflect.TypeOf(w).Name())
- }
- <-cn.CloseNotify()
- reqDoneMu.Lock()
- reqDone = true
- reqDoneMu.Unlock()
- })
-
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("Couldn't setup listener: %v", err)
- }
- addr := lis.Addr().String()
-
- srv := &http.Server{
- Handler: mux,
- }
- go srv.Serve(lis)
-
- cli := &Client{
- c: &http.Client{},
- conns: []*conn{
- &conn{
- url: "http://" + addr + "/",
- },
- },
- snifferEnabled: true,
- }
-
- type closer interface {
- Shutdown(context.Context) error
- }
-
- // pre-Go1.8 Server can't Shutdown
- cl, isServerCloseable := (interface{}(srv)).(closer)
-
- // Since Go1.7 can't Shutdown() - there will be leak from server
- // Monitor leaks on Go 1.8+
- if isServerCloseable {
- defer leaktest.CheckTimeout(t, time.Second*10)()
- }
-
- cli.sniff(time.Millisecond * 500)
-
- if isServerCloseable {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
- defer cancel()
- cl.Shutdown(ctx)
- }
-
- <-time.After(time.Second)
- reqDoneMu.Lock()
- if !reqDone {
- reqDoneMu.Unlock()
- t.Fatal("Request wasn't canceled or stopped")
- }
- reqDoneMu.Unlock()
-}
-
-func TestClientExtractHostname(t *testing.T) {
- tests := []struct {
- Scheme string
- Address string
- Output string
- }{
- {
- Scheme: "http",
- Address: "",
- Output: "",
- },
- {
- Scheme: "https",
- Address: "abc",
- Output: "",
- },
- {
- Scheme: "http",
- Address: "127.0.0.1:19200",
- Output: "http://127.0.0.1:19200",
- },
- {
- Scheme: "https",
- Address: "127.0.0.1:9200",
- Output: "https://127.0.0.1:9200",
- },
- {
- Scheme: "http",
- Address: "myelk.local/10.1.0.24:9200",
- Output: "http://10.1.0.24:9200",
- },
- }
-
- client, err := NewClient(SetSniff(false), SetHealthcheck(false))
- if err != nil {
- t.Fatal(err)
- }
- for _, test := range tests {
- got := client.extractHostname(test.Scheme, test.Address)
- if want := test.Output; want != got {
- t.Errorf("expected %q; got: %q", want, got)
- }
- }
-}
-
-// -- Selector --
-
-func TestClientSelectConnHealthy(t *testing.T) {
- client, err := NewClient(
- SetSniff(false),
- SetHealthcheck(false),
- SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
-
- // Both are healthy, so we should get both URLs in round-robin
- client.conns[0].MarkAsHealthy()
- client.conns[1].MarkAsHealthy()
-
- // #1: Return 1st
- c, err := client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[0].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
- }
- // #2: Return 2nd
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[1].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
- }
- // #3: Return 1st
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[0].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
- }
-}
-
-func TestClientSelectConnHealthyAndDead(t *testing.T) {
- client, err := NewClient(
- SetSniff(false),
- SetHealthcheck(false),
- SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
-
- // 1st is healthy, second is dead
- client.conns[0].MarkAsHealthy()
- client.conns[1].MarkAsDead()
-
- // #1: Return 1st
- c, err := client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[0].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
- }
- // #2: Return 1st again
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[0].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
- }
- // #3: Return 1st again and again
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[0].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[0].URL())
- }
-}
-
-func TestClientSelectConnDeadAndHealthy(t *testing.T) {
- client, err := NewClient(
- SetSniff(false),
- SetHealthcheck(false),
- SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
-
- // 1st is dead, 2nd is healthy
- client.conns[0].MarkAsDead()
- client.conns[1].MarkAsHealthy()
-
- // #1: Return 2nd
- c, err := client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[1].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
- }
- // #2: Return 2nd again
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[1].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
- }
- // #3: Return 2nd again and again
- c, err = client.next()
- if err != nil {
- t.Fatal(err)
- }
- if c.URL() != client.conns[1].URL() {
- t.Fatalf("expected %s; got: %s", c.URL(), client.conns[1].URL())
- }
-}
-
-func TestClientSelectConnAllDead(t *testing.T) {
- client, err := NewClient(
- SetSniff(false),
- SetHealthcheck(false),
- SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"))
- if err != nil {
- t.Fatal(err)
- }
-
- // Both are dead
- client.conns[0].MarkAsDead()
- client.conns[1].MarkAsDead()
-
- // If all connections are dead, next should make them alive again, but
- // still return an error when it first finds out.
- c, err := client.next()
- if !IsConnErr(err) {
- t.Fatal(err)
- }
- if c != nil {
- t.Fatalf("expected no connection; got: %v", c)
- }
- // Return a connection
- c, err = client.next()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if c == nil {
- t.Fatalf("expected connection; got: %v", c)
- }
- // Return a connection
- c, err = client.next()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if c == nil {
- t.Fatalf("expected connection; got: %v", c)
- }
-}
-
-// -- ElasticsearchVersion --
-
-func TestElasticsearchVersion(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- version, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if version == "" {
- t.Errorf("expected a version number, got: %q", version)
- }
-}
-
-// -- IndexNames --
-
-func TestIndexNames(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- names, err := client.IndexNames()
- if err != nil {
- t.Fatal(err)
- }
- if len(names) == 0 {
- t.Fatalf("expected some index names, got: %d", len(names))
- }
- var found bool
- for _, name := range names {
- if name == testIndexName {
- found = true
- break
- }
- }
- if !found {
- t.Fatalf("expected to find index %q; got: %v", testIndexName, found)
- }
-}
-
-// -- PerformRequest --
-
-func TestPerformRequest(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-}
-
-func TestPerformRequestWithSimpleClient(t *testing.T) {
- client, err := NewSimpleClient()
- if err != nil {
- t.Fatal(err)
- }
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-}
-
-func TestPerformRequestWithLogger(t *testing.T) {
- var w bytes.Buffer
- out := log.New(&w, "LOGGER ", log.LstdFlags)
-
- client, err := NewClient(SetInfoLog(out), SetSniff(false))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-
- got := w.String()
- pattern := `^LOGGER \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} GET http://.*/ \[status:200, request:\d+\.\d{3}s\]\n`
- matched, err := regexp.MatchString(pattern, got)
- if err != nil {
- t.Fatalf("expected log line to match %q; got: %v", pattern, err)
- }
- if !matched {
- t.Errorf("expected log line to match %q; got: %v", pattern, got)
- }
-}
-
-func TestPerformRequestWithLoggerAndTracer(t *testing.T) {
- var lw bytes.Buffer
- lout := log.New(&lw, "LOGGER ", log.LstdFlags)
-
- var tw bytes.Buffer
- tout := log.New(&tw, "TRACER ", log.LstdFlags)
-
- client, err := NewClient(SetInfoLog(lout), SetTraceLog(tout), SetSniff(false))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-
- lgot := lw.String()
- if lgot == "" {
- t.Errorf("expected logger output; got: %q", lgot)
- }
-
- tgot := tw.String()
- if tgot == "" {
- t.Errorf("expected tracer output; got: %q", tgot)
- }
-}
-func TestPerformRequestWithTracerOnError(t *testing.T) {
- var tw bytes.Buffer
- tout := log.New(&tw, "TRACER ", log.LstdFlags)
-
- client, err := NewClient(SetTraceLog(tout), SetSniff(false))
- if err != nil {
- t.Fatal(err)
- }
-
- client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/no-such-index",
- })
-
- tgot := tw.String()
- if tgot == "" {
- t.Errorf("expected tracer output; got: %q", tgot)
- }
-}
-
-type customLogger struct {
- out bytes.Buffer
-}
-
-func (l *customLogger) Printf(format string, v ...interface{}) {
- l.out.WriteString(fmt.Sprintf(format, v...) + "\n")
-}
-
-func TestPerformRequestWithCustomLogger(t *testing.T) {
- logger := &customLogger{}
-
- client, err := NewClient(SetInfoLog(logger), SetSniff(false))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-
- got := logger.out.String()
- pattern := `^GET http://.*/ \[status:200, request:\d+\.\d{3}s\]\n`
- matched, err := regexp.MatchString(pattern, got)
- if err != nil {
- t.Fatalf("expected log line to match %q; got: %v", pattern, err)
- }
- if !matched {
- t.Errorf("expected log line to match %q; got: %v", pattern, got)
- }
-}
-
-// failingTransport will run a fail callback if it sees a given URL path prefix.
-type failingTransport struct {
- path string // path prefix to look for
- fail func(*http.Request) (*http.Response, error) // call when path prefix is found
- next http.RoundTripper // next round-tripper (use http.DefaultTransport if nil)
-}
-
-// RoundTrip implements a failing transport.
-func (tr *failingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
- if strings.HasPrefix(r.URL.Path, tr.path) && tr.fail != nil {
- return tr.fail(r)
- }
- if tr.next != nil {
- return tr.next.RoundTrip(r)
- }
- return http.DefaultTransport.RoundTrip(r)
-}
-
-func TestPerformRequestRetryOnHttpError(t *testing.T) {
- var numFailedReqs int
- fail := func(r *http.Request) (*http.Response, error) {
- numFailedReqs += 1
- //return &http.Response{Request: r, StatusCode: 400}, nil
- return nil, errors.New("request failed")
- }
-
- // Run against a failing endpoint and see if PerformRequest
- // retries correctly.
- tr := &failingTransport{path: "/fail", fail: fail}
- httpClient := &http.Client{Transport: tr}
-
- client, err := NewClient(SetHttpClient(httpClient), SetMaxRetries(5), SetHealthcheck(false))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/fail",
- })
- if err == nil {
- t.Fatal("expected error")
- }
- if res != nil {
- t.Fatal("expected no response")
- }
- // Connection should be marked as dead after it failed
- if numFailedReqs != 5 {
- t.Errorf("expected %d failed requests; got: %d", 5, numFailedReqs)
- }
-}
-
-func TestPerformRequestNoRetryOnValidButUnsuccessfulHttpStatus(t *testing.T) {
- var numFailedReqs int
- fail := func(r *http.Request) (*http.Response, error) {
- numFailedReqs += 1
- return &http.Response{Request: r, StatusCode: 500}, nil
- }
-
- // Run against a failing endpoint and see if PerformRequest
- // retries correctly.
- tr := &failingTransport{path: "/fail", fail: fail}
- httpClient := &http.Client{Transport: tr}
-
- client, err := NewClient(SetHttpClient(httpClient), SetMaxRetries(5), SetHealthcheck(false))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/fail",
- })
- if err == nil {
- t.Fatal("expected error")
- }
- if res == nil {
- t.Fatal("expected response, got nil")
- }
- if want, got := 500, res.StatusCode; want != got {
- t.Fatalf("expected status code = %d, got %d", want, got)
- }
- // Retry should not have triggered additional requests because
- if numFailedReqs != 1 {
- t.Errorf("expected %d failed requests; got: %d", 1, numFailedReqs)
- }
-}
-
-// failingBody will return an error when json.Marshal is called on it.
-type failingBody struct{}
-
-// MarshalJSON implements the json.Marshaler interface and always returns an error.
-func (fb failingBody) MarshalJSON() ([]byte, error) {
- return nil, errors.New("failing to marshal")
-}
-
-func TestPerformRequestWithSetBodyError(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- Body: failingBody{},
- })
- if err == nil {
- t.Fatal("expected error")
- }
- if res != nil {
- t.Fatal("expected no response")
- }
-}
-
-// sleepingTransport will sleep before doing a request.
-type sleepingTransport struct {
- timeout time.Duration
-}
-
-// RoundTrip implements a "sleepy" transport.
-func (tr *sleepingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
- time.Sleep(tr.timeout)
- return http.DefaultTransport.RoundTrip(r)
-}
-
-func TestPerformRequestWithCancel(t *testing.T) {
- tr := &sleepingTransport{timeout: 3 * time.Second}
- httpClient := &http.Client{Transport: tr}
-
- client, err := NewSimpleClient(SetHttpClient(httpClient), SetMaxRetries(0))
- if err != nil {
- t.Fatal(err)
- }
-
- type result struct {
- res *Response
- err error
- }
- ctx, cancel := context.WithCancel(context.Background())
-
- resc := make(chan result, 1)
- go func() {
- res, err := client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- resc <- result{res: res, err: err}
- }()
- select {
- case <-time.After(1 * time.Second):
- cancel()
- case res := <-resc:
- t.Fatalf("expected response before cancel, got %v", res)
- case <-ctx.Done():
- t.Fatalf("expected no early termination, got ctx.Done(): %v", ctx.Err())
- }
- err = ctx.Err()
- if err != context.Canceled {
- t.Fatalf("expected error context.Canceled, got: %v", err)
- }
-}
-
-func TestPerformRequestWithTimeout(t *testing.T) {
- tr := &sleepingTransport{timeout: 3 * time.Second}
- httpClient := &http.Client{Transport: tr}
-
- client, err := NewSimpleClient(SetHttpClient(httpClient), SetMaxRetries(0))
- if err != nil {
- t.Fatal(err)
- }
-
- type result struct {
- res *Response
- err error
- }
- ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
- defer cancel()
-
- resc := make(chan result, 1)
- go func() {
- res, err := client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- resc <- result{res: res, err: err}
- }()
- select {
- case res := <-resc:
- t.Fatalf("expected timeout before response, got %v", res)
- case <-ctx.Done():
- err := ctx.Err()
- if err != context.DeadlineExceeded {
- t.Fatalf("expected error context.DeadlineExceeded, got: %v", err)
- }
- }
-}
-
-// -- Compression --
-
-// Notice that the trace log does always print "Accept-Encoding: gzip"
-// regardless of whether compression is enabled or not. This is because
-// of the underlying "httputil.DumpRequestOut".
-//
-// Use a real HTTP proxy/recorder to convince yourself that
-// "Accept-Encoding: gzip" is NOT sent when DisableCompression
-// is set to true.
-//
-// See also:
-// https://groups.google.com/forum/#!topic/golang-nuts/ms8QNCzew8Q
-
-func TestPerformRequestWithCompressionEnabled(t *testing.T) {
- testPerformRequestWithCompression(t, &http.Client{
- Transport: &http.Transport{
- DisableCompression: true,
- },
- })
-}
-
-func TestPerformRequestWithCompressionDisabled(t *testing.T) {
- testPerformRequestWithCompression(t, &http.Client{
- Transport: &http.Transport{
- DisableCompression: false,
- },
- })
-}
-
-func testPerformRequestWithCompression(t *testing.T, hc *http.Client) {
- client, err := NewClient(SetHttpClient(hc), SetSniff(false))
- if err != nil {
- t.Fatal(err)
- }
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/",
- })
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response to be != nil")
- }
-
- ret := new(PingResult)
- if err := json.Unmarshal(res.Body, ret); err != nil {
- t.Fatalf("expected no error on decode; got: %v", err)
- }
- if ret.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", ret.ClusterName)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/Makefile b/vendor/gopkg.in/olivere/elastic.v5/cluster-test/Makefile
deleted file mode 100644
index cc6261db5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-.PHONY: build run-omega-cluster-test
-
-default: build
-
-build:
- go build cluster-test.go
-
-run-omega-cluster-test:
- go run -race cluster-test.go \
- -nodes=http://192.168.2.65:8200,http://192.168.2.64:8200 \
- -n=5 \
- -retries=5 \
- -sniff=true -sniffer=10s \
- -healthcheck=true -healthchecker=5s \
- -errorlog=errors.log
-
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/README.md b/vendor/gopkg.in/olivere/elastic.v5/cluster-test/README.md
deleted file mode 100644
index f10748cc2..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/README.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Cluster Test
-
-This directory contains a program you can use to test a cluster.
-
-Here's how:
-
-First, install a cluster of Elasticsearch nodes. You can install them on
-different computers, or start several nodes on a single machine.
-
-Build cluster-test by `go build cluster-test.go` (or build with `make`).
-
-Run `./cluster-test -h` to get a list of flags:
-
-```sh
-$ ./cluster-test -h
-Usage of ./cluster-test:
- -errorlog="": error log file
- -healthcheck=true: enable or disable healthchecks
- -healthchecker=1m0s: healthcheck interval
- -index="twitter": name of ES index to use
- -infolog="": info log file
- -n=5: number of goroutines that run searches
- -nodes="": comma-separated list of ES URLs (e.g. 'http://192.168.2.10:9200,http://192.168.2.11:9200')
- -retries=0: number of retries
- -sniff=true: enable or disable sniffer
- -sniffer=15m0s: sniffer interval
- -tracelog="": trace log file
-```
-
-Example:
-
-```sh
-$ ./cluster-test -nodes=http://127.0.0.1:9200,http://127.0.0.1:9201,http://127.0.0.1:9202 -n=5 -index=twitter -retries=5 -sniff=true -sniffer=10s -healthcheck=true -healthchecker=5s -errorlog=error.log
-```
-
-The above example will create an index and start some search jobs on the
-cluster defined by http://127.0.0.1:9200, http://127.0.0.1:9201,
-and http://127.0.0.1:9202.
-
-* It will create an index called `twitter` on the cluster (`-index=twitter`)
-* It will run 5 search jobs in parallel (`-n=5`).
-* It will retry failed requests 5 times (`-retries=5`).
-* It will sniff the cluster periodically (`-sniff=true`).
-* It will sniff the cluster every 10 seconds (`-sniffer=10s`).
-* It will perform health checks periodically (`-healthcheck=true`).
-* It will perform health checks on the nodes every 5 seconds (`-healthchecker=5s`).
-* It will write an error log file (`-errorlog=error.log`).
-
-If you want to test Elastic with nodes going up and down, you can use a
-chaos monkey script like this and run it on the nodes of your cluster:
-
-```sh
-#!/bin/bash
-while true
-do
- echo "Starting ES node"
- elasticsearch -d -Xmx4g -Xms1g -Des.config=elasticsearch.yml -p es.pid
- sleep `jot -r 1 10 300` # wait for 10-300s
- echo "Stopping ES node"
- kill -TERM `cat es.pid`
- sleep `jot -r 1 10 60` # wait for 10-60s
-done
-```
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/cluster-test.go b/vendor/gopkg.in/olivere/elastic.v5/cluster-test/cluster-test.go
deleted file mode 100644
index 96b0c5d9b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster-test/cluster-test.go
+++ /dev/null
@@ -1,361 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package main
-
-import (
- "context"
- "encoding/json"
- "errors"
- "flag"
- "fmt"
- "log"
- "math/rand"
- "os"
- "runtime"
- "strings"
- "sync/atomic"
- "time"
-
- elastic "github.com/olivere/elastic"
-)
-
-type Tweet struct {
- User string `json:"user"`
- Message string `json:"message"`
- Retweets int `json:"retweets"`
- Image string `json:"image,omitempty"`
- Created time.Time `json:"created,omitempty"`
- Tags []string `json:"tags,omitempty"`
- Location string `json:"location,omitempty"`
- Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
-}
-
-var (
- nodes = flag.String("nodes", "", "comma-separated list of ES URLs (e.g. 'http://192.168.2.10:9200,http://192.168.2.11:9200')")
- n = flag.Int("n", 5, "number of goroutines that run searches")
- index = flag.String("index", "twitter", "name of ES index to use")
- errorlogfile = flag.String("errorlog", "", "error log file")
- infologfile = flag.String("infolog", "", "info log file")
- tracelogfile = flag.String("tracelog", "", "trace log file")
- retries = flag.Int("retries", 0, "number of retries")
- sniff = flag.Bool("sniff", elastic.DefaultSnifferEnabled, "enable or disable sniffer")
- sniffer = flag.Duration("sniffer", elastic.DefaultSnifferInterval, "sniffer interval")
- healthcheck = flag.Bool("healthcheck", elastic.DefaultHealthcheckEnabled, "enable or disable healthchecks")
- healthchecker = flag.Duration("healthchecker", elastic.DefaultHealthcheckInterval, "healthcheck interval")
-)
-
-func main() {
- flag.Parse()
-
- runtime.GOMAXPROCS(runtime.NumCPU())
-
- if *nodes == "" {
- log.Fatal("no nodes specified")
- }
- urls := strings.SplitN(*nodes, ",", -1)
-
- testcase, err := NewTestCase(*index, urls)
- if err != nil {
- log.Fatal(err)
- }
-
- testcase.SetErrorLogFile(*errorlogfile)
- testcase.SetInfoLogFile(*infologfile)
- testcase.SetTraceLogFile(*tracelogfile)
- testcase.SetMaxRetries(*retries)
- testcase.SetHealthcheck(*healthcheck)
- testcase.SetHealthcheckInterval(*healthchecker)
- testcase.SetSniff(*sniff)
- testcase.SetSnifferInterval(*sniffer)
-
- if err := testcase.Run(*n); err != nil {
- log.Fatal(err)
- }
-
- select {}
-}
-
-type RunInfo struct {
- Success bool
-}
-
-type TestCase struct {
- nodes []string
- client *elastic.Client
- runs int64
- failures int64
- runCh chan RunInfo
- index string
- errorlogfile string
- infologfile string
- tracelogfile string
- maxRetries int
- healthcheck bool
- healthcheckInterval time.Duration
- sniff bool
- snifferInterval time.Duration
-}
-
-func NewTestCase(index string, nodes []string) (*TestCase, error) {
- if index == "" {
- return nil, errors.New("no index name specified")
- }
-
- return &TestCase{
- index: index,
- nodes: nodes,
- runCh: make(chan RunInfo),
- }, nil
-}
-
-func (t *TestCase) SetIndex(name string) {
- t.index = name
-}
-
-func (t *TestCase) SetErrorLogFile(name string) {
- t.errorlogfile = name
-}
-
-func (t *TestCase) SetInfoLogFile(name string) {
- t.infologfile = name
-}
-
-func (t *TestCase) SetTraceLogFile(name string) {
- t.tracelogfile = name
-}
-
-func (t *TestCase) SetMaxRetries(n int) {
- t.maxRetries = n
-}
-
-func (t *TestCase) SetSniff(enabled bool) {
- t.sniff = enabled
-}
-
-func (t *TestCase) SetSnifferInterval(d time.Duration) {
- t.snifferInterval = d
-}
-
-func (t *TestCase) SetHealthcheck(enabled bool) {
- t.healthcheck = enabled
-}
-
-func (t *TestCase) SetHealthcheckInterval(d time.Duration) {
- t.healthcheckInterval = d
-}
-
-func (t *TestCase) Run(n int) error {
- if err := t.setup(); err != nil {
- return err
- }
-
- for i := 1; i < n; i++ {
- go t.search()
- }
-
- go t.monitor()
-
- return nil
-}
-
-func (t *TestCase) monitor() {
- print := func() {
- fmt.Printf("\033[32m%5d\033[0m; \033[31m%5d\033[0m: %s%s\r", t.runs, t.failures, t.client.String(), " ")
- }
-
- for {
- select {
- case run := <-t.runCh:
- atomic.AddInt64(&t.runs, 1)
- if !run.Success {
- atomic.AddInt64(&t.failures, 1)
- fmt.Println()
- }
- print()
- case <-time.After(5 * time.Second):
- // Print stats after some inactivity
- print()
- break
- }
- }
-}
-
-func (t *TestCase) setup() error {
- var errorlogger *log.Logger
- if t.errorlogfile != "" {
- f, err := os.OpenFile(t.errorlogfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
- if err != nil {
- return err
- }
- errorlogger = log.New(f, "", log.Ltime|log.Lmicroseconds|log.Lshortfile)
- }
-
- var infologger *log.Logger
- if t.infologfile != "" {
- f, err := os.OpenFile(t.infologfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
- if err != nil {
- return err
- }
- infologger = log.New(f, "", log.LstdFlags)
- }
-
- // Trace request and response details like this
- var tracelogger *log.Logger
- if t.tracelogfile != "" {
- f, err := os.OpenFile(t.tracelogfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
- if err != nil {
- return err
- }
- tracelogger = log.New(f, "", log.LstdFlags)
- }
-
- client, err := elastic.NewClient(
- elastic.SetURL(t.nodes...),
- elastic.SetErrorLog(errorlogger),
- elastic.SetInfoLog(infologger),
- elastic.SetTraceLog(tracelogger),
- elastic.SetMaxRetries(t.maxRetries),
- elastic.SetSniff(t.sniff),
- elastic.SetSnifferInterval(t.snifferInterval),
- elastic.SetHealthcheck(t.healthcheck),
- elastic.SetHealthcheckInterval(t.healthcheckInterval))
- if err != nil {
- // Handle error
- return err
- }
- t.client = client
-
- ctx := context.Background()
-
- // Use the IndexExists service to check if a specified index exists.
- exists, err := t.client.IndexExists(t.index).Do(ctx)
- if err != nil {
- return err
- }
- if exists {
- deleteIndex, err := t.client.DeleteIndex(t.index).Do(ctx)
- if err != nil {
- return err
- }
- if !deleteIndex.Acknowledged {
- return errors.New("delete index not acknowledged")
- }
- }
-
- // Create a new index.
- createIndex, err := t.client.CreateIndex(t.index).Do(ctx)
- if err != nil {
- return err
- }
- if !createIndex.Acknowledged {
- return errors.New("create index not acknowledged")
- }
-
- // Index a tweet (using JSON serialization)
- tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
- _, err = t.client.Index().
- Index(t.index).
- Type("tweet").
- Id("1").
- BodyJson(tweet1).
- Do(ctx)
- if err != nil {
- return err
- }
-
- // Index a second tweet (by string)
- tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}`
- _, err = t.client.Index().
- Index(t.index).
- Type("tweet").
- Id("2").
- BodyString(tweet2).
- Do(ctx)
- if err != nil {
- return err
- }
-
- // Flush to make sure the documents got written.
- _, err = t.client.Flush().Index(t.index).Do(ctx)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (t *TestCase) search() {
- ctx := context.Background()
-
- // Loop forever to check for connection issues
- for {
- // Get tweet with specified ID
- get1, err := t.client.Get().
- Index(t.index).
- Type("tweet").
- Id("1").
- Do(ctx)
- if err != nil {
- //failf("Get failed: %v", err)
- t.runCh <- RunInfo{Success: false}
- continue
- }
- if !get1.Found {
- //log.Printf("Document %s not found\n", "1")
- //fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
- t.runCh <- RunInfo{Success: false}
- continue
- }
-
- // Search with a term query
- searchResult, err := t.client.Search().
- Index(t.index). // search in index t.index
- Query(elastic.NewTermQuery("user", "olivere")). // specify the query
- Sort("user", true). // sort by "user" field, ascending
- From(0).Size(10). // take documents 0-9
- Pretty(true). // pretty print request and response JSON
- Do(ctx) // execute
- if err != nil {
- //failf("Search failed: %v\n", err)
- t.runCh <- RunInfo{Success: false}
- continue
- }
-
- // searchResult is of type SearchResult and returns hits, suggestions,
- // and all kinds of other information from Elasticsearch.
- //fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
-
- // Number of hits
- if searchResult.Hits.TotalHits > 0 {
- //fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
-
- // Iterate through results
- for _, hit := range searchResult.Hits.Hits {
- // hit.Index contains the name of the index
-
- // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
- var tweet Tweet
- err := json.Unmarshal(*hit.Source, &tweet)
- if err != nil {
- // Deserialization failed
- //failf("Deserialize failed: %v\n", err)
- t.runCh <- RunInfo{Success: false}
- continue
- }
-
- // Work with tweet
- //fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- } else {
- // No hits
- //fmt.Print("Found no tweets\n")
- }
-
- t.runCh <- RunInfo{Success: true}
-
- // Sleep some time
- time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_health.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_health.go
index f960cfe8e..a3ee72cd1 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_health.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/cluster_health.go
@@ -10,7 +10,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// ClusterHealthService allows to get a very simple status on the health of the cluster.
@@ -131,7 +131,7 @@ func (s *ClusterHealthService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.level != "" {
params.Set("level", s.level)
@@ -179,11 +179,7 @@ func (s *ClusterHealthService) Do(ctx context.Context) (*ClusterHealthResponse,
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_health_test.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_health_test.go
deleted file mode 100644
index c2caee985..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_health_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "net/url"
- "testing"
-)
-
-func TestClusterHealth(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Get cluster health
- res, err := client.ClusterHealth().Index(testIndexName).Level("shards").Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected res to be != nil; got: %v", res)
- }
- if res.Status != "green" && res.Status != "red" && res.Status != "yellow" {
- t.Fatalf("expected status \"green\", \"red\", or \"yellow\"; got: %q", res.Status)
- }
-}
-
-func TestClusterHealthURLs(t *testing.T) {
- tests := []struct {
- Service *ClusterHealthService
- ExpectedPath string
- ExpectedParams url.Values
- }{
- {
- Service: &ClusterHealthService{
- indices: []string{},
- },
- ExpectedPath: "/_cluster/health",
- },
- {
- Service: &ClusterHealthService{
- indices: []string{"twitter"},
- },
- ExpectedPath: "/_cluster/health/twitter",
- },
- {
- Service: &ClusterHealthService{
- indices: []string{"twitter", "gplus"},
- },
- ExpectedPath: "/_cluster/health/twitter%2Cgplus",
- },
- {
- Service: &ClusterHealthService{
- indices: []string{"twitter"},
- waitForStatus: "yellow",
- },
- ExpectedPath: "/_cluster/health/twitter",
- ExpectedParams: url.Values{"wait_for_status": []string{"yellow"}},
- },
- }
-
- for _, test := range tests {
- gotPath, gotParams, err := test.Service.buildURL()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if gotPath != test.ExpectedPath {
- t.Errorf("expected URL path = %q; got: %q", test.ExpectedPath, gotPath)
- }
- if gotParams.Encode() != test.ExpectedParams.Encode() {
- t.Errorf("expected URL params = %v; got: %v", test.ExpectedParams, gotParams)
- }
- }
-}
-
-func TestClusterHealthWaitForStatus(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- // Ensure preconditions are met: A green cluster.
- health, err := client.ClusterHealth().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if got, want := health.Status, "green"; got != want {
- t.Skipf("precondition failed: expected cluster to be %q, not %q", want, got)
- }
-
- // Cluster health on an index that does not exist should never get to yellow
- health, err = client.ClusterHealth().Index("no-such-index").WaitForStatus("yellow").Timeout("1s").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected timeout error; got: %v", err)
- }
- if !IsTimeout(err) {
- t.Fatalf("expected timeout error; got: %v", err)
- }
- if health != nil {
- t.Fatalf("expected no response; got: %v", health)
- }
-
- // Cluster wide health
- health, err = client.ClusterHealth().WaitForGreenStatus().Timeout("10s").Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if health.TimedOut != false {
- t.Fatalf("expected no timeout; got: %v "+
- "(does your local cluster contain unassigned shards?)", health.TimedOut)
- }
- if health.Status != "green" {
- t.Fatalf("expected health = %q; got: %q", "green", health.Status)
- }
-
- // Cluster wide health via shortcut on client
- err = client.WaitForGreenStatus("10s")
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_state.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_state.go
index 54e9aa428..d6e608211 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_state.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/cluster_state.go
@@ -10,12 +10,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// ClusterStateService allows to get a comprehensive state information of the whole cluster.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/cluster-state.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-state.html
// for details.
type ClusterStateService struct {
client *Client
@@ -123,7 +123,7 @@ func (s *ClusterStateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
@@ -165,11 +165,7 @@ func (s *ClusterStateService) Do(ctx context.Context) (*ClusterStateResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
@@ -239,10 +235,10 @@ type clusterStateRoutingNode struct {
}
type indexTemplateMetaData struct {
- IndexPatterns []string `json:"index_patterns"` // e.g. ["store-*"]
- Order int `json:"order"`
- Settings map[string]interface{} `json:"settings"` // index settings
- Mappings map[string]interface{} `json:"mappings"` // type name -> mapping
+ Template string `json:"template"` // e.g. "store-*"
+ Order int `json:"order"`
+ Settings map[string]interface{} `json:"settings"` // index settings
+ Mappings map[string]interface{} `json:"mappings"` // type name -> mapping
}
type indexMetaData struct {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_state_test.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_state_test.go
deleted file mode 100644
index 6eedb0c1b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_state_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "net/url"
- "testing"
-)
-
-func TestClusterState(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Get cluster state
- res, err := client.ClusterState().Index("_all").Metric("_all").Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected res to be != nil; got: %v", res)
- }
- if res.ClusterName == "" {
- t.Fatalf("expected a cluster name; got: %q", res.ClusterName)
- }
-}
-
-func TestClusterStateURLs(t *testing.T) {
- tests := []struct {
- Service *ClusterStateService
- ExpectedPath string
- ExpectedParams url.Values
- }{
- {
- Service: &ClusterStateService{
- indices: []string{},
- metrics: []string{},
- },
- ExpectedPath: "/_cluster/state/_all/_all",
- },
- {
- Service: &ClusterStateService{
- indices: []string{"twitter"},
- metrics: []string{},
- },
- ExpectedPath: "/_cluster/state/_all/twitter",
- },
- {
- Service: &ClusterStateService{
- indices: []string{"twitter", "gplus"},
- metrics: []string{},
- },
- ExpectedPath: "/_cluster/state/_all/twitter%2Cgplus",
- },
- {
- Service: &ClusterStateService{
- indices: []string{},
- metrics: []string{"nodes"},
- },
- ExpectedPath: "/_cluster/state/nodes/_all",
- },
- {
- Service: &ClusterStateService{
- indices: []string{"twitter"},
- metrics: []string{"nodes"},
- },
- ExpectedPath: "/_cluster/state/nodes/twitter",
- },
- {
- Service: &ClusterStateService{
- indices: []string{"twitter"},
- metrics: []string{"nodes"},
- masterTimeout: "1s",
- },
- ExpectedPath: "/_cluster/state/nodes/twitter",
- ExpectedParams: url.Values{"master_timeout": []string{"1s"}},
- },
- }
-
- for _, test := range tests {
- gotPath, gotParams, err := test.Service.buildURL()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if gotPath != test.ExpectedPath {
- t.Errorf("expected URL path = %q; got: %q", test.ExpectedPath, gotPath)
- }
- if gotParams.Encode() != test.ExpectedParams.Encode() {
- t.Errorf("expected URL params = %v; got: %v", test.ExpectedParams, gotParams)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_stats.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_stats.go
index 4d05c2e97..8c5374d0f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/cluster_stats.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// ClusterStatsService is documented at
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/cluster-stats.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-stats.html.
type ClusterStatsService struct {
client *Client
pretty bool
@@ -78,7 +78,7 @@ func (s *ClusterStatsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.flatSettings != nil {
params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings))
@@ -108,11 +108,7 @@ func (s *ClusterStatsService) Do(ctx context.Context) (*ClusterStatsResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
@@ -179,8 +175,10 @@ type ClusterStatsIndicesDocs struct {
}
type ClusterStatsIndicesStore struct {
- Size string `json:"size"` // e.g. "5.3gb"
- SizeInBytes int64 `json:"size_in_bytes"`
+ Size string `json:"size"` // e.g. "5.3gb"
+ SizeInBytes int64 `json:"size_in_bytes"`
+ ThrottleTime string `json:"throttle_time"` // e.g. "0s"
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis"`
}
type ClusterStatsIndicesFieldData struct {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/cluster_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/cluster_stats_test.go
deleted file mode 100644
index fe6da4704..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/cluster_stats_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "net/url"
- "testing"
-)
-
-func TestClusterStats(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Get cluster stats
- res, err := client.ClusterStats().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected res to be != nil; got: %v", res)
- }
- if res.ClusterName == "" {
- t.Fatalf("expected a cluster name; got: %q", res.ClusterName)
- }
- if res.Nodes == nil {
- t.Fatalf("expected nodes; got: %v", res.Nodes)
- }
- if res.Nodes.Count == nil {
- t.Fatalf("expected nodes count; got: %v", res.Nodes.Count)
- }
-}
-
-func TestClusterStatsURLs(t *testing.T) {
- fFlag := false
- tFlag := true
-
- tests := []struct {
- Service *ClusterStatsService
- ExpectedPath string
- ExpectedParams url.Values
- }{
- {
- Service: &ClusterStatsService{
- nodeId: []string{},
- },
- ExpectedPath: "/_cluster/stats",
- },
- {
- Service: &ClusterStatsService{
- nodeId: []string{"node1"},
- },
- ExpectedPath: "/_cluster/stats/nodes/node1",
- },
- {
- Service: &ClusterStatsService{
- nodeId: []string{"node1", "node2"},
- },
- ExpectedPath: "/_cluster/stats/nodes/node1%2Cnode2",
- },
- {
- Service: &ClusterStatsService{
- nodeId: []string{},
- flatSettings: &tFlag,
- },
- ExpectedPath: "/_cluster/stats",
- ExpectedParams: url.Values{"flat_settings": []string{"true"}},
- },
- {
- Service: &ClusterStatsService{
- nodeId: []string{"node1"},
- flatSettings: &fFlag,
- },
- ExpectedPath: "/_cluster/stats/nodes/node1",
- ExpectedParams: url.Values{"flat_settings": []string{"false"}},
- },
- }
-
- for _, test := range tests {
- gotPath, gotParams, err := test.Service.buildURL()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if gotPath != test.ExpectedPath {
- t.Errorf("expected URL path = %q; got: %q", test.ExpectedPath, gotPath)
- }
- if gotParams.Encode() != test.ExpectedParams.Encode() {
- t.Errorf("expected URL params = %v; got: %v", test.ExpectedParams, gotParams)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/config/config_test.go b/vendor/gopkg.in/olivere/elastic.v5/config/config_test.go
deleted file mode 100644
index caa3bbadb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/config/config_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package config
-
-import "testing"
-
-func TestParse(t *testing.T) {
- urls := "http://user:pwd@elastic:19220/store-blobs?shards=5&replicas=2&sniff=true&errorlog=elastic.error.log&infolog=elastic.info.log&tracelog=elastic.trace.log"
- cfg, err := Parse(urls)
- if err != nil {
- t.Fatal(err)
- }
- if want, got := "http://elastic:19220", cfg.URL; want != got {
- t.Fatalf("expected URL = %q, got %q", want, got)
- }
- if want, got := "store-blobs", cfg.Index; want != got {
- t.Fatalf("expected Index = %q, got %q", want, got)
- }
- if want, got := "user", cfg.Username; want != got {
- t.Fatalf("expected Username = %q, got %q", want, got)
- }
- if want, got := "pwd", cfg.Password; want != got {
- t.Fatalf("expected Password = %q, got %q", want, got)
- }
- if want, got := 5, cfg.Shards; want != got {
- t.Fatalf("expected Shards = %v, got %v", want, got)
- }
- if want, got := 2, cfg.Replicas; want != got {
- t.Fatalf("expected Replicas = %v, got %v", want, got)
- }
- if want, got := true, *cfg.Sniff; want != got {
- t.Fatalf("expected Sniff = %v, got %v", want, got)
- }
- if want, got := "elastic.error.log", cfg.Errorlog; want != got {
- t.Fatalf("expected Errorlog = %q, got %q", want, got)
- }
- if want, got := "elastic.info.log", cfg.Infolog; want != got {
- t.Fatalf("expected Infolog = %q, got %q", want, got)
- }
- if want, got := "elastic.trace.log", cfg.Tracelog; want != got {
- t.Fatalf("expected Tracelog = %q, got %q", want, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/count.go b/vendor/gopkg.in/olivere/elastic.v5/count.go
index 44416fab0..d7aca4801 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/count.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/count.go
@@ -8,9 +8,10 @@ import (
"context"
"fmt"
"net/url"
+ "strconv"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// CountService is a convenient service for determining the
@@ -35,6 +36,7 @@ type CountService struct {
q string
query Query
routing string
+ terminateAfter *int
bodyJson interface{}
bodyString string
}
@@ -158,6 +160,13 @@ func (s *CountService) Routing(routing string) *CountService {
return s
}
+// TerminateAfter indicates the maximum count for each shard, upon reaching
+// which the query execution will terminate early.
+func (s *CountService) TerminateAfter(terminateAfter int) *CountService {
+ s.terminateAfter = &terminateAfter
+ return s
+}
+
// Pretty indicates that the JSON response be indented and human readable.
func (s *CountService) Pretty(pretty bool) *CountService {
s.pretty = pretty
@@ -207,7 +216,7 @@ func (s *CountService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
@@ -248,6 +257,9 @@ func (s *CountService) buildURL() (string, url.Values, error) {
if s.routing != "" {
params.Set("routing", s.routing)
}
+ if s.terminateAfter != nil {
+ params.Set("terminate_after", strconv.Itoa(*s.terminateAfter))
+ }
return path, params, nil
}
@@ -286,12 +298,7 @@ func (s *CountService) Do(ctx context.Context) (int64, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return 0, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/count_test.go b/vendor/gopkg.in/olivere/elastic.v5/count_test.go
deleted file mode 100644
index a0ee52112..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/count_test.go
+++ /dev/null
@@ -1,127 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestCountURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_all/_count",
- },
- {
- []string{},
- []string{"tweet"},
- "/_all/tweet/_count",
- },
- {
- []string{"twitter-*"},
- []string{"tweet", "follower"},
- "/twitter-%2A/tweet%2Cfollower/_count",
- },
- {
- []string{"twitter-2014", "twitter-2015"},
- []string{"tweet", "follower"},
- "/twitter-2014%2Ctwitter-2015/tweet%2Cfollower/_count",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.Count().Index(test.Indices...).Type(test.Types...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestCount(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Count documents
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Errorf("expected Count = %d; got %d", 3, count)
- }
-
- // Count documents
- count, err = client.Count(testIndexName).Type("doc").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Errorf("expected Count = %d; got %d", 3, count)
- }
-
- // Count documents
- count, err = client.Count(testIndexName).Type("gezwitscher").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 0 {
- t.Errorf("expected Count = %d; got %d", 0, count)
- }
-
- // Count with query
- query := NewTermQuery("user", "olivere")
- count, err = client.Count(testIndexName).Query(query).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 2 {
- t.Errorf("expected Count = %d; got %d", 2, count)
- }
-
- // Count with query and type
- query = NewTermQuery("user", "olivere")
- count, err = client.Count(testIndexName).Type("doc").Query(query).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 2 {
- t.Errorf("expected Count = %d; got %d", 2, count)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/decoder_test.go b/vendor/gopkg.in/olivere/elastic.v5/decoder_test.go
deleted file mode 100644
index 2c3dde8ca..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/decoder_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "sync/atomic"
- "testing"
-)
-
-type decoder struct {
- dec json.Decoder
-
- N int64
-}
-
-func (d *decoder) Decode(data []byte, v interface{}) error {
- atomic.AddInt64(&d.N, 1)
- dec := json.NewDecoder(bytes.NewReader(data))
- dec.UseNumber()
- return dec.Decode(v)
-}
-
-func TestDecoder(t *testing.T) {
- dec := &decoder{}
- client := setupTestClientAndCreateIndex(t, SetDecoder(dec), SetMaxRetries(0))
-
- tweet := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // Add a document
- indexResult, err := client.Index().
- Index(testIndexName).
- Type("doc").
- Id("1").
- BodyJson(&tweet).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexResult == nil {
- t.Errorf("expected result to be != nil; got: %v", indexResult)
- }
- if dec.N == 0 {
- t.Errorf("expected at least 1 call of decoder; got: %d", dec.N)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/delete.go b/vendor/gopkg.in/olivere/elastic.v5/delete.go
index 1e20de11f..3efdce46b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/delete.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/delete.go
@@ -7,16 +7,17 @@ package elastic
import (
"context"
"fmt"
- "net/http"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "net/http"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// DeleteService allows to delete a typed JSON document from a specified
// index based on its id.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-delete.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-delete.html
// for details.
type DeleteService struct {
client *Client
@@ -125,7 +126,7 @@ func (s *DeleteService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.refresh != "" {
params.Set("refresh", s.refresh)
@@ -185,12 +186,7 @@ func (s *DeleteService) Do(ctx context.Context) (*DeleteResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- IgnoreErrors: []int{http.StatusNotFound},
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil, http.StatusNotFound)
if err != nil {
return nil, err
}
@@ -223,4 +219,5 @@ type DeleteResponse struct {
PrimaryTerm int64 `json:"_primary_term,omitempty"`
Status int `json:"status,omitempty"`
ForcedRefresh bool `json:"forced_refresh,omitempty"`
+ Found bool `json:"found,omitempty"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/delete_by_query.go b/vendor/gopkg.in/olivere/elastic.v5/delete_by_query.go
index 694d81c2a..a890bd84f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/delete_by_query.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/delete_by_query.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// DeleteByQueryService deletes documents that match a query.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-delete-by-query.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-delete-by-query.html.
type DeleteByQueryService struct {
client *Client
index []string
@@ -598,12 +598,7 @@ func (s *DeleteByQueryService) Do(ctx context.Context) (*BulkIndexByScrollRespon
}
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/delete_by_query_test.go b/vendor/gopkg.in/olivere/elastic.v5/delete_by_query_test.go
deleted file mode 100644
index 40e45b871..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/delete_by_query_test.go
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestDeleteByQueryBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- ExpectErr bool
- }{
- {
- []string{},
- []string{},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{},
- "/index1/_delete_by_query",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{},
- "/index1%2Cindex2/_delete_by_query",
- false,
- },
- {
- []string{},
- []string{"type1"},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{"type1"},
- "/index1/type1/_delete_by_query",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{"type1", "type2"},
- "/index1%2Cindex2/type1%2Ctype2/_delete_by_query",
- false,
- },
- }
-
- for i, test := range tests {
- builder := client.DeleteByQuery().Index(test.Indices...).Type(test.Types...)
- err := builder.Validate()
- if err != nil {
- if !test.ExpectErr {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- } else {
- // err == nil
- if test.ExpectErr {
- t.Errorf("case #%d: expected error", i+1)
- continue
- }
- path, _, _ := builder.buildURL()
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
- }
-}
-
-func TestDeleteByQuery(t *testing.T) {
- // client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Count documents
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Fatalf("expected count = %d; got: %d", 3, count)
- }
-
- // Delete all documents by sandrae
- q := NewTermQuery("user", "sandrae")
- res, err := client.DeleteByQuery().
- Index(testIndexName).
- Type("doc").
- Query(q).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected response != nil; got: %v", res)
- }
-
- // Flush and check count
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err = client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 2 {
- t.Fatalf("expected Count = %d; got: %d", 2, count)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/delete_template.go b/vendor/gopkg.in/olivere/elastic.v5/delete_template.go
new file mode 100644
index 000000000..4775baf84
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/delete_template.go
@@ -0,0 +1,109 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// DeleteTemplateService deletes a search template. More information can
+// be found at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-template.html.
+type DeleteTemplateService struct {
+ client *Client
+ pretty bool
+ id string
+ version *int
+ versionType string
+}
+
+// NewDeleteTemplateService creates a new DeleteTemplateService.
+func NewDeleteTemplateService(client *Client) *DeleteTemplateService {
+ return &DeleteTemplateService{
+ client: client,
+ }
+}
+
+// Id is the template ID.
+func (s *DeleteTemplateService) Id(id string) *DeleteTemplateService {
+ s.id = id
+ return s
+}
+
+// Version an explicit version number for concurrency control.
+func (s *DeleteTemplateService) Version(version int) *DeleteTemplateService {
+ s.version = &version
+ return s
+}
+
+// VersionType specifies a version type.
+func (s *DeleteTemplateService) VersionType(versionType string) *DeleteTemplateService {
+ s.versionType = versionType
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *DeleteTemplateService) buildURL() (string, url.Values, error) {
+ // Build URL
+ path, err := uritemplates.Expand("/_search/template/{id}", map[string]string{
+ "id": s.id,
+ })
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.version != nil {
+ params.Set("version", fmt.Sprintf("%d", *s.version))
+ }
+ if s.versionType != "" {
+ params.Set("version_type", s.versionType)
+ }
+
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *DeleteTemplateService) Validate() error {
+ var invalid []string
+ if s.id == "" {
+ invalid = append(invalid, "Id")
+ }
+ if len(invalid) > 0 {
+ return fmt.Errorf("missing required fields: %v", invalid)
+ }
+ return nil
+}
+
+// Do executes the operation.
+func (s *DeleteTemplateService) Do(ctx context.Context) (*AcknowledgedResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return operation response
+ ret := new(AcknowledgedResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/delete_test.go b/vendor/gopkg.in/olivere/elastic.v5/delete_test.go
deleted file mode 100644
index 571fcf589..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/delete_test.go
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestDelete(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Count documents
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Errorf("expected Count = %d; got %d", 3, count)
- }
-
- // Delete document 1
- res, err := client.Delete().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if want, have := "deleted", res.Result; want != have {
- t.Errorf("expected Result = %q; got %q", want, have)
- }
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- count, err = client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 2 {
- t.Errorf("expected Count = %d; got %d", 2, count)
- }
-
- // Delete non existent document 99
- res, err = client.Delete().Index(testIndexName).Type("doc").Id("99").Refresh("true").Do(context.TODO())
- if err == nil {
- t.Fatal("expected error")
- }
- if !IsNotFound(err) {
- t.Fatalf("expected 404, got: %v", err)
- }
- if _, ok := err.(*Error); !ok {
- t.Fatalf("expected error type *Error, got: %T", err)
- }
- if res == nil {
- t.Fatal("expected response")
- }
- if have, want := res.Id, "99"; have != want {
- t.Errorf("expected _id = %q, got %q", have, want)
- }
- if have, want := res.Index, testIndexName; have != want {
- t.Errorf("expected _index = %q, got %q", have, want)
- }
- if have, want := res.Type, "doc"; have != want {
- t.Errorf("expected _type = %q, got %q", have, want)
- }
- if have, want := res.Result, "not_found"; have != want {
- t.Errorf("expected Result = %q, got %q", have, want)
- }
-
- count, err = client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 2 {
- t.Errorf("expected Count = %d; got %d", 2, count)
- }
-}
-
-func TestDeleteValidate(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // No index name -> fail with error
- res, err := NewDeleteService(client).Type("doc").Id("1").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-
- // No type -> fail with error
- res, err = NewDeleteService(client).Index(testIndexName).Id("1").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without type")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-
- // No id -> fail with error
- res, err = NewDeleteService(client).Index(testIndexName).Type("doc").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without id")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/errors_test.go b/vendor/gopkg.in/olivere/elastic.v5/errors_test.go
deleted file mode 100644
index 75d3949e5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/errors_test.go
+++ /dev/null
@@ -1,295 +0,0 @@
-package elastic
-
-import (
- "bufio"
- "fmt"
- "net/http"
- "strings"
- "testing"
-)
-
-func TestResponseError(t *testing.T) {
- raw := "HTTP/1.1 404 Not Found\r\n" +
- "\r\n" +
- `{"error":{"root_cause":[{"type":"index_missing_exception","reason":"no such index","index":"elastic-test"}],"type":"index_missing_exception","reason":"no such index","index":"elastic-test"},"status":404}` + "\r\n"
- r := bufio.NewReader(strings.NewReader(raw))
-
- req, err := http.NewRequest("GET", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := http.ReadResponse(r, nil)
- if err != nil {
- t.Fatal(err)
- }
- err = checkResponse(req, resp)
- if err == nil {
- t.Fatalf("expected error; got: %v", err)
- }
-
- // Check for correct error message
- expected := fmt.Sprintf("elastic: Error %d (%s): no such index [type=index_missing_exception]", resp.StatusCode, http.StatusText(resp.StatusCode))
- got := err.Error()
- if got != expected {
- t.Fatalf("expected %q; got: %q", expected, got)
- }
-
- // Check that error is of type *elastic.Error, which contains additional information
- e, ok := err.(*Error)
- if !ok {
- t.Fatal("expected error to be of type *elastic.Error")
- }
- if e.Status != resp.StatusCode {
- t.Fatalf("expected status code %d; got: %d", resp.StatusCode, e.Status)
- }
- if e.Details == nil {
- t.Fatalf("expected error details; got: %v", e.Details)
- }
- if got, want := e.Details.Index, "elastic-test"; got != want {
- t.Fatalf("expected error details index %q; got: %q", want, got)
- }
- if got, want := e.Details.Type, "index_missing_exception"; got != want {
- t.Fatalf("expected error details type %q; got: %q", want, got)
- }
- if got, want := e.Details.Reason, "no such index"; got != want {
- t.Fatalf("expected error details reason %q; got: %q", want, got)
- }
- if got, want := len(e.Details.RootCause), 1; got != want {
- t.Fatalf("expected %d error details root causes; got: %d", want, got)
- }
-
- if got, want := e.Details.RootCause[0].Index, "elastic-test"; got != want {
- t.Fatalf("expected root cause index %q; got: %q", want, got)
- }
- if got, want := e.Details.RootCause[0].Type, "index_missing_exception"; got != want {
- t.Fatalf("expected root cause type %q; got: %q", want, got)
- }
- if got, want := e.Details.RootCause[0].Reason, "no such index"; got != want {
- t.Fatalf("expected root cause reason %q; got: %q", want, got)
- }
-}
-
-func TestResponseErrorHTML(t *testing.T) {
- raw := "HTTP/1.1 413 Request Entity Too Large\r\n" +
- "\r\n" +
- `<html>
-<head><title>413 Request Entity Too Large</title></head>
-<body bgcolor="white">
-<center><h1>413 Request Entity Too Large</h1></center>
-<hr><center>nginx/1.6.2</center>
-</body>
-</html>` + "\r\n"
- r := bufio.NewReader(strings.NewReader(raw))
-
- req, err := http.NewRequest("GET", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := http.ReadResponse(r, nil)
- if err != nil {
- t.Fatal(err)
- }
- err = checkResponse(req, resp)
- if err == nil {
- t.Fatalf("expected error; got: %v", err)
- }
-
- // Check for correct error message
- expected := fmt.Sprintf("elastic: Error %d (%s)", http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge))
- got := err.Error()
- if got != expected {
- t.Fatalf("expected %q; got: %q", expected, got)
- }
-}
-
-func TestResponseErrorWithIgnore(t *testing.T) {
- raw := "HTTP/1.1 404 Not Found\r\n" +
- "\r\n" +
- `{"some":"response"}` + "\r\n"
- r := bufio.NewReader(strings.NewReader(raw))
-
- req, err := http.NewRequest("HEAD", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := http.ReadResponse(r, nil)
- if err != nil {
- t.Fatal(err)
- }
- err = checkResponse(req, resp)
- if err == nil {
- t.Fatalf("expected error; got: %v", err)
- }
- err = checkResponse(req, resp, 404) // ignore 404 errors
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
-}
-
-func TestIsNotFound(t *testing.T) {
- if got, want := IsNotFound(nil), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(""), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(200), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(404), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsNotFound(&Error{Status: 404}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(&Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsNotFound(Error{Status: 404}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsNotFound(&http.Response{StatusCode: 404}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsNotFound(&http.Response{StatusCode: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-}
-
-func TestIsTimeout(t *testing.T) {
- if got, want := IsTimeout(nil), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(""), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(200), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(408), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsTimeout(&Error{Status: 408}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(&Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsTimeout(Error{Status: 408}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsTimeout(&http.Response{StatusCode: 408}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsTimeout(&http.Response{StatusCode: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-}
-
-func TestIsConflict(t *testing.T) {
- if got, want := IsConflict(nil), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(""), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(200), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(http.StatusConflict), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsConflict(&Error{Status: 409}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(&Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsConflict(Error{Status: 409}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(Error{Status: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-
- if got, want := IsConflict(&http.Response{StatusCode: 409}), true; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
- if got, want := IsConflict(&http.Response{StatusCode: 200}), false; got != want {
- t.Errorf("expected %v; got: %v", want, got)
- }
-}
-
-func TestIsStatusCode(t *testing.T) {
- tests := []struct {
- Error interface{}
- Code int
- Want bool
- }{
- // #0
- {
- Error: nil,
- Code: 200,
- Want: false,
- },
- // #1
- {
- Error: "",
- Code: 200,
- Want: false,
- },
- // #2
- {
- Error: http.StatusConflict,
- Code: 409,
- Want: true,
- },
- // #3
- {
- Error: http.StatusConflict,
- Code: http.StatusInternalServerError,
- Want: false,
- },
- // #4
- {
- Error: &Error{Status: http.StatusConflict},
- Code: 409,
- Want: true,
- },
- // #5
- {
- Error: Error{Status: http.StatusConflict},
- Code: 409,
- Want: true,
- },
- // #6
- {
- Error: &http.Response{StatusCode: http.StatusConflict},
- Code: 409,
- Want: true,
- },
- }
-
- for i, tt := range tests {
- if have, want := IsStatusCode(tt.Error, tt.Code), tt.Want; have != want {
- t.Errorf("#%d: have %v, want %v", i, have, want)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/etc/elasticsearch.yml b/vendor/gopkg.in/olivere/elastic.v5/etc/elasticsearch.yml
deleted file mode 100644
index 9923cfe4f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/etc/elasticsearch.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-# bootstrap.ignore_system_bootstrap_checks: true
-
-discovery.zen.minimum_master_nodes: 1
-
-network.host:
-- _local_
-- _site_
-
-network.publish_host: _local_
-
-
-# Enable scripting as described here: https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html
-script.inline: true
-script.stored: true
-script.file: true
diff --git a/vendor/gopkg.in/olivere/elastic.v5/etc/ingest-geoip/.gitkeep b/vendor/gopkg.in/olivere/elastic.v5/etc/ingest-geoip/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/etc/ingest-geoip/.gitkeep
+++ /dev/null
diff --git a/vendor/gopkg.in/olivere/elastic.v5/etc/jvm.options b/vendor/gopkg.in/olivere/elastic.v5/etc/jvm.options
deleted file mode 100644
index d97fbc9ec..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/etc/jvm.options
+++ /dev/null
@@ -1,100 +0,0 @@
-## JVM configuration
-
-################################################################
-## IMPORTANT: JVM heap size
-################################################################
-##
-## You should always set the min and max JVM heap
-## size to the same value. For example, to set
-## the heap to 4 GB, set:
-##
-## -Xms4g
-## -Xmx4g
-##
-## See https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html
-## for more information
-##
-################################################################
-
-# Xms represents the initial size of total heap space
-# Xmx represents the maximum size of total heap space
-
--Xms2g
--Xmx2g
-
-################################################################
-## Expert settings
-################################################################
-##
-## All settings below this section are considered
-## expert settings. Don't tamper with them unless
-## you understand what you are doing
-##
-################################################################
-
-## GC configuration
--XX:+UseConcMarkSweepGC
--XX:CMSInitiatingOccupancyFraction=75
--XX:+UseCMSInitiatingOccupancyOnly
-
-## optimizations
-
-# disable calls to System#gc
--XX:+DisableExplicitGC
-
-# pre-touch memory pages used by the JVM during initialization
--XX:+AlwaysPreTouch
-
-## basic
-
-# force the server VM
--server
-
-# set to headless, just in case
--Djava.awt.headless=true
-
-# ensure UTF-8 encoding by default (e.g. filenames)
--Dfile.encoding=UTF-8
-
-# use our provided JNA always versus the system one
--Djna.nosys=true
-
-# flags to keep Netty from being unsafe
--Dio.netty.noUnsafe=true
--Dio.netty.noKeySetOptimization=true
-
-# log4j 2
--Dlog4j.shutdownHookEnabled=false
--Dlog4j2.disable.jmx=true
--Dlog4j.skipJansi=true
-
-## heap dumps
-
-# generate a heap dump when an allocation from the Java heap fails
-# heap dumps are created in the working directory of the JVM
--XX:+HeapDumpOnOutOfMemoryError
-
-# specify an alternative path for heap dumps
-# ensure the directory exists and has sufficient space
-#-XX:HeapDumpPath=${heap.dump.path}
-
-## GC logging
-
-#-XX:+PrintGCDetails
-#-XX:+PrintGCTimeStamps
-#-XX:+PrintGCDateStamps
-#-XX:+PrintClassHistogram
-#-XX:+PrintTenuringDistribution
-#-XX:+PrintGCApplicationStoppedTime
-
-# log GC status to a file with time stamps
-# ensure the directory exists
-#-Xloggc:${loggc}
-
-# Elasticsearch 5.0.0 will throw an exception on unquoted field names in JSON.
-# If documents were already indexed with unquoted fields in a previous version
-# of Elasticsearch, some operations may throw errors.
-#
-# WARNING: This option will be removed in Elasticsearch 6.0.0 and is provided
-# only for migration purposes.
-#-Delasticsearch.json.allow_unquoted_field_names=true
diff --git a/vendor/gopkg.in/olivere/elastic.v5/etc/log4j2.properties b/vendor/gopkg.in/olivere/elastic.v5/etc/log4j2.properties
deleted file mode 100644
index 9a3147f5a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/etc/log4j2.properties
+++ /dev/null
@@ -1,74 +0,0 @@
-status = error
-
-# log action execution errors for easier debugging
-logger.action.name = org.elasticsearch.action
-logger.action.level = debug
-
-appender.console.type = Console
-appender.console.name = console
-appender.console.layout.type = PatternLayout
-appender.console.layout.pattern = [%d{ISO8601}][%-5p][%-25c{1.}] %marker%m%n
-
-appender.rolling.type = RollingFile
-appender.rolling.name = rolling
-appender.rolling.fileName = ${sys:es.logs}.log
-appender.rolling.layout.type = PatternLayout
-appender.rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c{1.}] %marker%.10000m%n
-appender.rolling.filePattern = ${sys:es.logs}-%d{yyyy-MM-dd}.log
-appender.rolling.policies.type = Policies
-appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
-appender.rolling.policies.time.interval = 1
-appender.rolling.policies.time.modulate = true
-
-rootLogger.level = info
-rootLogger.appenderRef.console.ref = console
-rootLogger.appenderRef.rolling.ref = rolling
-
-appender.deprecation_rolling.type = RollingFile
-appender.deprecation_rolling.name = deprecation_rolling
-appender.deprecation_rolling.fileName = ${sys:es.logs}_deprecation.log
-appender.deprecation_rolling.layout.type = PatternLayout
-appender.deprecation_rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c{1.}] %marker%.10000m%n
-appender.deprecation_rolling.filePattern = ${sys:es.logs}_deprecation-%i.log.gz
-appender.deprecation_rolling.policies.type = Policies
-appender.deprecation_rolling.policies.size.type = SizeBasedTriggeringPolicy
-appender.deprecation_rolling.policies.size.size = 1GB
-appender.deprecation_rolling.strategy.type = DefaultRolloverStrategy
-appender.deprecation_rolling.strategy.max = 4
-
-logger.deprecation.name = org.elasticsearch.deprecation
-logger.deprecation.level = warn
-logger.deprecation.appenderRef.deprecation_rolling.ref = deprecation_rolling
-logger.deprecation.additivity = false
-
-appender.index_search_slowlog_rolling.type = RollingFile
-appender.index_search_slowlog_rolling.name = index_search_slowlog_rolling
-appender.index_search_slowlog_rolling.fileName = ${sys:es.logs}_index_search_slowlog.log
-appender.index_search_slowlog_rolling.layout.type = PatternLayout
-appender.index_search_slowlog_rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %marker%.10000m%n
-appender.index_search_slowlog_rolling.filePattern = ${sys:es.logs}_index_search_slowlog-%d{yyyy-MM-dd}.log
-appender.index_search_slowlog_rolling.policies.type = Policies
-appender.index_search_slowlog_rolling.policies.time.type = TimeBasedTriggeringPolicy
-appender.index_search_slowlog_rolling.policies.time.interval = 1
-appender.index_search_slowlog_rolling.policies.time.modulate = true
-
-logger.index_search_slowlog_rolling.name = index.search.slowlog
-logger.index_search_slowlog_rolling.level = trace
-logger.index_search_slowlog_rolling.appenderRef.index_search_slowlog_rolling.ref = index_search_slowlog_rolling
-logger.index_search_slowlog_rolling.additivity = false
-
-appender.index_indexing_slowlog_rolling.type = RollingFile
-appender.index_indexing_slowlog_rolling.name = index_indexing_slowlog_rolling
-appender.index_indexing_slowlog_rolling.fileName = ${sys:es.logs}_index_indexing_slowlog.log
-appender.index_indexing_slowlog_rolling.layout.type = PatternLayout
-appender.index_indexing_slowlog_rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %marker%.10000m%n
-appender.index_indexing_slowlog_rolling.filePattern = ${sys:es.logs}_index_indexing_slowlog-%d{yyyy-MM-dd}.log
-appender.index_indexing_slowlog_rolling.policies.type = Policies
-appender.index_indexing_slowlog_rolling.policies.time.type = TimeBasedTriggeringPolicy
-appender.index_indexing_slowlog_rolling.policies.time.interval = 1
-appender.index_indexing_slowlog_rolling.policies.time.modulate = true
-
-logger.index_indexing_slowlog.name = index.indexing.slowlog.index
-logger.index_indexing_slowlog.level = trace
-logger.index_indexing_slowlog.appenderRef.index_indexing_slowlog_rolling.ref = index_indexing_slowlog_rolling
-logger.index_indexing_slowlog.additivity = false
diff --git a/vendor/gopkg.in/olivere/elastic.v5/etc/scripts/.gitkeep b/vendor/gopkg.in/olivere/elastic.v5/etc/scripts/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/etc/scripts/.gitkeep
+++ /dev/null
diff --git a/vendor/gopkg.in/olivere/elastic.v5/example_test.go b/vendor/gopkg.in/olivere/elastic.v5/example_test.go
deleted file mode 100644
index 62dc15d89..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/example_test.go
+++ /dev/null
@@ -1,530 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic_test
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "os"
- "reflect"
- "time"
-
- elastic "github.com/olivere/elastic"
-)
-
-type Tweet struct {
- User string `json:"user"`
- Message string `json:"message"`
- Retweets int `json:"retweets"`
- Image string `json:"image,omitempty"`
- Created time.Time `json:"created,omitempty"`
- Tags []string `json:"tags,omitempty"`
- Location string `json:"location,omitempty"`
- Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
-}
-
-func Example() {
- errorlog := log.New(os.Stdout, "APP ", log.LstdFlags)
-
- // Obtain a client. You can also provide your own HTTP client here.
- client, err := elastic.NewClient(elastic.SetErrorLog(errorlog))
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Trace request and response details like this
- //client.SetTracer(log.New(os.Stdout, "", 0))
-
- // Ping the Elasticsearch server to get e.g. the version number
- info, code, err := client.Ping("http://127.0.0.1:9200").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
-
- // Getting the ES version number is quite common, so there's a shortcut
- esversion, err := client.ElasticsearchVersion("http://127.0.0.1:9200")
- if err != nil {
- // Handle error
- panic(err)
- }
- fmt.Printf("Elasticsearch version %s\n", esversion)
-
- // Use the IndexExists service to check if a specified index exists.
- exists, err := client.IndexExists("twitter").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if !exists {
- // Create a new index.
- mapping := `
-{
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "user":{
- "type":"keyword"
- },
- "message":{
- "type":"text",
- "store": true,
- "fielddata": true
- },
- "retweets":{
- "type":"long"
- },
- "tags":{
- "type":"keyword"
- },
- "location":{
- "type":"geo_point"
- },
- "suggest_field":{
- "type":"completion"
- }
- }
- }
- }
-}
-`
- createIndex, err := client.CreateIndex("twitter").Body(mapping).Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if !createIndex.Acknowledged {
- // Not acknowledged
- }
- }
-
- // Index a tweet (using JSON serialization)
- tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
- put1, err := client.Index().
- Index("twitter").
- Type("doc").
- Id("1").
- BodyJson(tweet1).
- Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
-
- // Index a second tweet (by string)
- tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}`
- put2, err := client.Index().
- Index("twitter").
- Type("doc").
- Id("2").
- BodyString(tweet2).
- Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- fmt.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type)
-
- // Get tweet with specified ID
- get1, err := client.Get().
- Index("twitter").
- Type("doc").
- Id("1").
- Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if get1.Found {
- fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
- }
-
- // Flush to make sure the documents got written.
- _, err = client.Flush().Index("twitter").Do(context.Background())
- if err != nil {
- panic(err)
- }
-
- // Search with a term query
- termQuery := elastic.NewTermQuery("user", "olivere")
- searchResult, err := client.Search().
- Index("twitter"). // search in index "twitter"
- Query(termQuery). // specify the query
- Sort("user", true). // sort by "user" field, ascending
- From(0).Size(10). // take documents 0-9
- Pretty(true). // pretty print request and response JSON
- Do(context.Background()) // execute
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // searchResult is of type SearchResult and returns hits, suggestions,
- // and all kinds of other information from Elasticsearch.
- fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
-
- // Each is a convenience function that iterates over hits in a search result.
- // It makes sure you don't need to check for nil values in the response.
- // However, it ignores errors in serialization. If you want full control
- // over iterating the hits, see below.
- var ttyp Tweet
- for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
- t := item.(Tweet)
- fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- // TotalHits is another convenience function that works even when something goes wrong.
- fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())
-
- // Here's how you iterate through results with full control over each step.
- if searchResult.Hits.TotalHits > 0 {
- fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
-
- // Iterate through results
- for _, hit := range searchResult.Hits.Hits {
- // hit.Index contains the name of the index
-
- // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
- var t Tweet
- err := json.Unmarshal(*hit.Source, &t)
- if err != nil {
- // Deserialization failed
- }
-
- // Work with tweet
- fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- } else {
- // No hits
- fmt.Print("Found no tweets\n")
- }
-
- // Update a tweet by the update API of Elasticsearch.
- // We just increment the number of retweets.
- script := elastic.NewScript("ctx._source.retweets += params.num").Param("num", 1)
- update, err := client.Update().Index("twitter").Type("doc").Id("1").
- Script(script).
- Upsert(map[string]interface{}{"retweets": 0}).
- Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- fmt.Printf("New version of tweet %q is now %d", update.Id, update.Version)
-
- // ...
-
- // Delete an index.
- deleteIndex, err := client.DeleteIndex("twitter").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if !deleteIndex.Acknowledged {
- // Not acknowledged
- }
-}
-
-func ExampleClient_NewClient_default() {
- // Obtain a client to the Elasticsearch instance on http://127.0.0.1:9200.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- fmt.Printf("connection failed: %v\n", err)
- } else {
- fmt.Println("connected")
- }
- _ = client
- // Output:
- // connected
-}
-
-func ExampleClient_NewClient_cluster() {
- // Obtain a client for an Elasticsearch cluster of two nodes,
- // running on 10.0.1.1 and 10.0.1.2.
- client, err := elastic.NewClient(elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200"))
- if err != nil {
- // Handle error
- panic(err)
- }
- _ = client
-}
-
-func ExampleClient_NewClient_manyOptions() {
- // Obtain a client for an Elasticsearch cluster of two nodes,
- // running on 10.0.1.1 and 10.0.1.2. Do not run the sniffer.
- // Set the healthcheck interval to 10s. When requests fail,
- // retry 5 times. Print error messages to os.Stderr and informational
- // messages to os.Stdout.
- client, err := elastic.NewClient(
- elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200"),
- elastic.SetSniff(false),
- elastic.SetHealthcheckInterval(10*time.Second),
- elastic.SetMaxRetries(5),
- elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
- elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)))
- if err != nil {
- // Handle error
- panic(err)
- }
- _ = client
-}
-
-func ExampleIndexExistsService() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
- // Use the IndexExists service to check if the index "twitter" exists.
- exists, err := client.IndexExists("twitter").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if exists {
- // ...
- }
-}
-
-func ExampleCreateIndexService() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
- // Create a new index.
- createIndex, err := client.CreateIndex("twitter").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if !createIndex.Acknowledged {
- // Not acknowledged
- }
-}
-
-func ExampleDeleteIndexService() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
- // Delete an index.
- deleteIndex, err := client.DeleteIndex("twitter").Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- if !deleteIndex.Acknowledged {
- // Not acknowledged
- }
-}
-
-func ExampleSearchService() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Search with a term query
- termQuery := elastic.NewTermQuery("user", "olivere")
- searchResult, err := client.Search().
- Index("twitter"). // search in index "twitter"
- Query(termQuery). // specify the query
- Sort("user", true). // sort by "user" field, ascending
- From(0).Size(10). // take documents 0-9
- Pretty(true). // pretty print request and response JSON
- Do(context.Background()) // execute
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // searchResult is of type SearchResult and returns hits, suggestions,
- // and all kinds of other information from Elasticsearch.
- fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
-
- // Number of hits
- if searchResult.Hits.TotalHits > 0 {
- fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
-
- // Iterate through results
- for _, hit := range searchResult.Hits.Hits {
- // hit.Index contains the name of the index
-
- // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
- var t Tweet
- err := json.Unmarshal(*hit.Source, &t)
- if err != nil {
- // Deserialization failed
- }
-
- // Work with tweet
- fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- } else {
- // No hits
- fmt.Print("Found no tweets\n")
- }
-}
-
-func ExampleAggregations() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Create an aggregation for users and a sub-aggregation for a date histogram of tweets (per year).
- timeline := elastic.NewTermsAggregation().Field("user").Size(10).OrderByCountDesc()
- histogram := elastic.NewDateHistogramAggregation().Field("created").Interval("year")
- timeline = timeline.SubAggregation("history", histogram)
-
- // Search with a term query
- searchResult, err := client.Search().
- Index("twitter"). // search in index "twitter"
- Query(elastic.NewMatchAllQuery()). // return all results, but ...
- SearchType("count"). // ... do not return hits, just the count
- Aggregation("timeline", timeline). // add our aggregation to the query
- Pretty(true). // pretty print request and response JSON
- Do(context.Background()) // execute
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Access "timeline" aggregate in search result.
- agg, found := searchResult.Aggregations.Terms("timeline")
- if !found {
- log.Fatalf("we should have a terms aggregation called %q", "timeline")
- }
- for _, userBucket := range agg.Buckets {
- // Every bucket should have the user field as key.
- user := userBucket.Key
-
- // The sub-aggregation history should have the number of tweets per year.
- histogram, found := userBucket.DateHistogram("history")
- if found {
- for _, year := range histogram.Buckets {
- fmt.Printf("user %q has %d tweets in %q\n", user, year.DocCount, year.KeyAsString)
- }
- }
- }
-}
-
-func ExampleSearchResult() {
- client, err := elastic.NewClient()
- if err != nil {
- panic(err)
- }
-
- // Do a search
- searchResult, err := client.Search().Index("twitter").Query(elastic.NewMatchAllQuery()).Do(context.Background())
- if err != nil {
- panic(err)
- }
-
- // searchResult is of type SearchResult and returns hits, suggestions,
- // and all kinds of other information from Elasticsearch.
- fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
-
- // Each is a utility function that iterates over hits in a search result.
- // It makes sure you don't need to check for nil values in the response.
- // However, it ignores errors in serialization. If you want full control
- // over iterating the hits, see below.
- var ttyp Tweet
- for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
- t := item.(Tweet)
- fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())
-
- // Here's how you iterate hits with full control.
- if searchResult.Hits.TotalHits > 0 {
- fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
-
- // Iterate through results
- for _, hit := range searchResult.Hits.Hits {
- // hit.Index contains the name of the index
-
- // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
- var t Tweet
- err := json.Unmarshal(*hit.Source, &t)
- if err != nil {
- // Deserialization failed
- }
-
- // Work with tweet
- fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
- }
- } else {
- // No hits
- fmt.Print("Found no tweets\n")
- }
-}
-
-func ExampleClusterHealthService() {
- client, err := elastic.NewClient()
- if err != nil {
- panic(err)
- }
-
- // Get cluster health
- res, err := client.ClusterHealth().Index("twitter").Do(context.Background())
- if err != nil {
- panic(err)
- }
- if res == nil {
- panic(err)
- }
- fmt.Printf("Cluster status is %q\n", res.Status)
-}
-
-func ExampleClusterHealthService_WaitForGreen() {
- client, err := elastic.NewClient()
- if err != nil {
- panic(err)
- }
-
- // Wait for status green
- res, err := client.ClusterHealth().WaitForStatus("green").Timeout("15s").Do(context.Background())
- if err != nil {
- panic(err)
- }
- if res.TimedOut {
- fmt.Printf("time out waiting for cluster status %q\n", "green")
- } else {
- fmt.Printf("cluster status is %q\n", res.Status)
- }
-}
-
-func ExampleClusterStateService() {
- client, err := elastic.NewClient()
- if err != nil {
- panic(err)
- }
-
- // Get cluster state
- res, err := client.ClusterState().Metric("version").Do(context.Background())
- if err != nil {
- panic(err)
- }
- fmt.Printf("Cluster %q has version %d", res.ClusterName, res.Version)
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/exists.go b/vendor/gopkg.in/olivere/elastic.v5/exists.go
index ae5a88fa7..7cae2bde8 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/exists.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/exists.go
@@ -10,12 +10,12 @@ import (
"net/http"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// ExistsService checks for the existence of a document using HEAD.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-get.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-get.html
// for details.
type ExistsService struct {
client *Client
@@ -107,7 +107,7 @@ func (s *ExistsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.realtime != nil {
params.Set("realtime", fmt.Sprintf("%v", *s.realtime))
@@ -159,12 +159,7 @@ func (s *ExistsService) Do(ctx context.Context) (bool, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "HEAD",
- Path: path,
- Params: params,
- IgnoreErrors: []int{404},
- })
+ res, err := s.client.PerformRequest(ctx, "HEAD", path, params, nil, 404)
if err != nil {
return false, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/exists_test.go b/vendor/gopkg.in/olivere/elastic.v5/exists_test.go
deleted file mode 100644
index 9b834223d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/exists_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestExists(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- exists, err := client.Exists().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Fatal("expected document to exist")
- }
-}
-
-func TestExistsValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index -> fail with error
- res, err := NewExistsService(client).Type("doc").Id("1").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without index name")
- }
- if res != false {
- t.Fatalf("expected result to be false; got: %v", res)
- }
-
- // No type -> fail with error
- res, err = NewExistsService(client).Index(testIndexName).Id("1").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without index name")
- }
- if res != false {
- t.Fatalf("expected result to be false; got: %v", res)
- }
-
- // No id -> fail with error
- res, err = NewExistsService(client).Index(testIndexName).Type("doc").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Delete to fail without index name")
- }
- if res != false {
- t.Fatalf("expected result to be false; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/explain.go b/vendor/gopkg.in/olivere/elastic.v5/explain.go
index 2b975ad5d..bdfa00f1d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/explain.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/explain.go
@@ -10,12 +10,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// ExplainService computes a score explanation for a query and
// a specific document.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-explain.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-explain.html.
type ExplainService struct {
client *Client
pretty bool
@@ -208,7 +208,7 @@ func (s *ExplainService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.xSource) > 0 {
params.Set("_source", strings.Join(s.xSource, ","))
@@ -298,12 +298,7 @@ func (s *ExplainService) Do(ctx context.Context) (*ExplainResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/explain_test.go b/vendor/gopkg.in/olivere/elastic.v5/explain_test.go
deleted file mode 100644
index 22cb9668a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/explain_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestExplain(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // Add a document
- indexResult, err := client.Index().
- Index(testIndexName).
- Type("doc").
- Id("1").
- BodyJson(&tweet1).
- Refresh("true").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexResult == nil {
- t.Errorf("expected result to be != nil; got: %v", indexResult)
- }
-
- // Explain
- query := NewTermQuery("user", "olivere")
- expl, err := client.Explain(testIndexName, "doc", "1").Query(query).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if expl == nil {
- t.Fatal("expected to return an explanation")
- }
- if !expl.Matched {
- t.Errorf("expected matched to be %v; got: %v", true, expl.Matched)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context.go b/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context.go
index 874c4c1da..53e7fcd90 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context.go
@@ -14,7 +14,7 @@ import (
// with various endpoints, e.g. when searching for documents, retrieving
// individual documents, or even updating documents.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-source-filtering.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-request-source-filtering.html
// for details.
type FetchSourceContext struct {
fetchSource bool
diff --git a/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context_test.go b/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context_test.go
deleted file mode 100644
index b98549036..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/fetch_source_context_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestFetchSourceContextNoFetchSource(t *testing.T) {
- builder := NewFetchSourceContext(false)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `false`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFetchSourceContextNoFetchSourceIgnoreIncludesAndExcludes(t *testing.T) {
- builder := NewFetchSourceContext(false).Include("a", "b").Exclude("c")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `false`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFetchSourceContextFetchSource(t *testing.T) {
- builder := NewFetchSourceContext(true)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `true`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFetchSourceContextFetchSourceWithIncludesOnly(t *testing.T) {
- builder := NewFetchSourceContext(true).Include("a", "b")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"includes":["a","b"]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFetchSourceContextFetchSourceWithIncludesAndExcludes(t *testing.T) {
- builder := NewFetchSourceContext(true).Include("a", "b").Exclude("c")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"excludes":["c"],"includes":["a","b"]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFetchSourceContextQueryDefaults(t *testing.T) {
- builder := NewFetchSourceContext(true)
- values := builder.Query()
- got := values.Encode()
- expected := ""
- if got != expected {
- t.Errorf("expected %q; got: %q", expected, got)
- }
-}
-
-func TestFetchSourceContextQueryNoFetchSource(t *testing.T) {
- builder := NewFetchSourceContext(false)
- values := builder.Query()
- got := values.Encode()
- expected := "_source=false"
- if got != expected {
- t.Errorf("expected %q; got: %q", expected, got)
- }
-}
-
-func TestFetchSourceContextQueryFetchSourceWithIncludesAndExcludes(t *testing.T) {
- builder := NewFetchSourceContext(true).Include("a", "b").Exclude("c")
- values := builder.Query()
- got := values.Encode()
- expected := "_source_exclude=c&_source_include=a%2Cb"
- if got != expected {
- t.Errorf("expected %q; got: %q", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/field_caps.go b/vendor/gopkg.in/olivere/elastic.v5/field_caps.go
index 393cd3ce8..78b343370 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/field_caps.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/field_caps.go
@@ -11,12 +11,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// FieldCapsService allows retrieving the capabilities of fields among multiple indices.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-field-caps.html
+// See http://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-field-caps.html
// for details
type FieldCapsService struct {
client *Client
@@ -152,13 +152,7 @@ func (s *FieldCapsService) Do(ctx context.Context) (*FieldCapsResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- IgnoreErrors: []int{http.StatusNotFound},
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body, http.StatusNotFound)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/field_caps_test.go b/vendor/gopkg.in/olivere/elastic.v5/field_caps_test.go
deleted file mode 100644
index e299fd516..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/field_caps_test.go
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "net/url"
- "reflect"
- "sort"
- "testing"
-)
-
-func TestFieldCapsURLs(t *testing.T) {
- tests := []struct {
- Service *FieldCapsService
- ExpectedPath string
- ExpectedParams url.Values
- }{
- {
- Service: &FieldCapsService{},
- ExpectedPath: "/_field_caps",
- ExpectedParams: url.Values{},
- },
- {
- Service: &FieldCapsService{
- index: []string{"index1", "index2"},
- },
- ExpectedPath: "/index1%2Cindex2/_field_caps",
- ExpectedParams: url.Values{},
- },
- {
- Service: &FieldCapsService{
- index: []string{"index_*"},
- pretty: true,
- },
- ExpectedPath: "/index_%2A/_field_caps",
- ExpectedParams: url.Values{"pretty": []string{"true"}},
- },
- }
-
- for _, test := range tests {
- gotPath, gotParams, err := test.Service.buildURL()
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if gotPath != test.ExpectedPath {
- t.Errorf("expected URL path = %q; got: %q", test.ExpectedPath, gotPath)
- }
- if gotParams.Encode() != test.ExpectedParams.Encode() {
- t.Errorf("expected URL params = %v; got: %v", test.ExpectedParams, gotParams)
- }
- }
-}
-
-func TestFieldCapsRequestSerialize(t *testing.T) {
- req := &FieldCapsRequest{
- Fields: []string{"creation_date", "answer_count"},
- }
- data, err := json.Marshal(req)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fields":["creation_date","answer_count"]}`
- if got != expected {
- t.Fatalf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldCapsRequestDeserialize(t *testing.T) {
- body := `{
- "fields" : ["creation_date", "answer_count"]
- }`
-
- var request FieldCapsRequest
- if err := json.Unmarshal([]byte(body), &request); err != nil {
- t.Fatalf("unexpected error during unmarshalling: %v", err)
- }
-
- sort.Sort(lexicographically{request.Fields})
-
- expectedFields := []string{"answer_count", "creation_date"}
- if !reflect.DeepEqual(request.Fields, expectedFields) {
- t.Fatalf("expected fields to be %v, got %v", expectedFields, request.Fields)
- }
-}
-
-func TestFieldCapsResponseUnmarshalling(t *testing.T) {
- clusterStats := `{
- "_shards": {
- "total": 1,
- "successful": 1,
- "failed": 0
- },
- "fields": {
- "creation_date": {
- "type": "date",
- "searchable": true,
- "aggregatable": true,
- "indices": ["index1", "index2"],
- "non_searchable_indices": null,
- "non_aggregatable_indices": null
- },
- "answer": {
- "type": "keyword",
- "searchable": true,
- "aggregatable": true
- }
- }
- }`
-
- var resp FieldCapsResponse
- if err := json.Unmarshal([]byte(clusterStats), &resp); err != nil {
- t.Errorf("unexpected error during unmarshalling: %v", err)
- }
-
- caps, ok := resp.Fields["creation_date"]
- if !ok {
- t.Errorf("expected creation_date to be in the fields map, didn't find it")
- }
- if want, have := true, caps.Searchable; want != have {
- t.Errorf("expected creation_date searchable to be %v, got %v", want, have)
- }
- if want, have := true, caps.Aggregatable; want != have {
- t.Errorf("expected creation_date aggregatable to be %v, got %v", want, have)
- }
- if want, have := []string{"index1", "index2"}, caps.Indices; !reflect.DeepEqual(want, have) {
- t.Errorf("expected creation_date indices to be %v, got %v", want, have)
- }
-}
-
-func TestFieldCaps123(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
- // client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- res, err := client.FieldCaps("_all").Fields("user", "message", "retweets", "created").Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if res == nil {
- t.Fatalf("expected response; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/field_stats.go b/vendor/gopkg.in/olivere/elastic.v5/field_stats.go
new file mode 100644
index 000000000..c2104c5cb
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/field_stats.go
@@ -0,0 +1,259 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+const (
+ FieldStatsClusterLevel = "cluster"
+ FieldStatsIndicesLevel = "indices"
+)
+
+// FieldStatsService allows finding statistical properties of a field without executing a search,
+// but looking up measurements that are natively available in the Lucene index.
+//
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-field-stats.html
+// for details
+type FieldStatsService struct {
+ client *Client
+ pretty bool
+ level string
+ index []string
+ allowNoIndices *bool
+ expandWildcards string
+ fields []string
+ ignoreUnavailable *bool
+ bodyJson interface{}
+ bodyString string
+}
+
+// NewFieldStatsService creates a new FieldStatsService
+func NewFieldStatsService(client *Client) *FieldStatsService {
+ return &FieldStatsService{
+ client: client,
+ index: make([]string, 0),
+ fields: make([]string, 0),
+ }
+}
+
+// Index is a list of index names; use `_all` or empty string to perform
+// the operation on all indices.
+func (s *FieldStatsService) Index(index ...string) *FieldStatsService {
+ s.index = append(s.index, index...)
+ return s
+}
+
+// AllowNoIndices indicates whether to ignore if a wildcard indices expression
+// resolves into no concrete indices.
+// (This includes `_all` string or when no indices have been specified).
+func (s *FieldStatsService) AllowNoIndices(allowNoIndices bool) *FieldStatsService {
+ s.allowNoIndices = &allowNoIndices
+ return s
+}
+
+// ExpandWildcards indicates whether to expand wildcard expression to
+// concrete indices that are open, closed or both.
+func (s *FieldStatsService) ExpandWildcards(expandWildcards string) *FieldStatsService {
+ s.expandWildcards = expandWildcards
+ return s
+}
+
+// Fields is a list of fields for to get field statistics
+// for (min value, max value, and more).
+func (s *FieldStatsService) Fields(fields ...string) *FieldStatsService {
+ s.fields = append(s.fields, fields...)
+ return s
+}
+
+// IgnoreUnavailable is documented as: Whether specified concrete indices should be ignored when unavailable (missing or closed).
+func (s *FieldStatsService) IgnoreUnavailable(ignoreUnavailable bool) *FieldStatsService {
+ s.ignoreUnavailable = &ignoreUnavailable
+ return s
+}
+
+// Level sets if stats should be returned on a per index level or on a cluster wide level;
+// should be one of 'cluster' or 'indices'; defaults to former
+func (s *FieldStatsService) Level(level string) *FieldStatsService {
+ s.level = level
+ return s
+}
+
+// ClusterLevel is a helper that sets Level to "cluster".
+func (s *FieldStatsService) ClusterLevel() *FieldStatsService {
+ s.level = FieldStatsClusterLevel
+ return s
+}
+
+// IndicesLevel is a helper that sets Level to "indices".
+func (s *FieldStatsService) IndicesLevel() *FieldStatsService {
+ s.level = FieldStatsIndicesLevel
+ return s
+}
+
+// Pretty indicates that the JSON response be indented and human readable.
+func (s *FieldStatsService) Pretty(pretty bool) *FieldStatsService {
+ s.pretty = pretty
+ return s
+}
+
+// BodyJson is documented as: Field json objects containing the name and optionally a range to filter out indices result, that have results outside the defined bounds.
+func (s *FieldStatsService) BodyJson(body interface{}) *FieldStatsService {
+ s.bodyJson = body
+ return s
+}
+
+// BodyString is documented as: Field json objects containing the name and optionally a range to filter out indices result, that have results outside the defined bounds.
+func (s *FieldStatsService) BodyString(body string) *FieldStatsService {
+ s.bodyString = body
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *FieldStatsService) buildURL() (string, url.Values, error) {
+ // Build URL
+ var err error
+ var path string
+ if len(s.index) > 0 {
+ path, err = uritemplates.Expand("/{index}/_field_stats", map[string]string{
+ "index": strings.Join(s.index, ","),
+ })
+ } else {
+ path = "/_field_stats"
+ }
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.allowNoIndices != nil {
+ params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
+ }
+ if s.expandWildcards != "" {
+ params.Set("expand_wildcards", s.expandWildcards)
+ }
+ if len(s.fields) > 0 {
+ params.Set("fields", strings.Join(s.fields, ","))
+ }
+ if s.ignoreUnavailable != nil {
+ params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
+ }
+ if s.level != "" {
+ params.Set("level", s.level)
+ }
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *FieldStatsService) Validate() error {
+ var invalid []string
+ if s.level != "" && (s.level != FieldStatsIndicesLevel && s.level != FieldStatsClusterLevel) {
+ invalid = append(invalid, "Level")
+ }
+ if len(invalid) != 0 {
+ return fmt.Errorf("missing or invalid required fields: %v", invalid)
+ }
+ return nil
+}
+
+// Do executes the operation.
+func (s *FieldStatsService) Do(ctx context.Context) (*FieldStatsResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Setup HTTP request body
+ var body interface{}
+ if s.bodyJson != nil {
+ body = s.bodyJson
+ } else {
+ body = s.bodyString
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body, http.StatusNotFound)
+ if err != nil {
+ return nil, err
+ }
+
+ // TODO(oe): Is 404 really a valid response here?
+ if res.StatusCode == http.StatusNotFound {
+ return &FieldStatsResponse{make(map[string]IndexFieldStats)}, nil
+ }
+
+ // Return operation response
+ ret := new(FieldStatsResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+// -- Request --
+
+// FieldStatsRequest can be used to set up the body to be used in the
+// Field Stats API.
+type FieldStatsRequest struct {
+ Fields []string `json:"fields"`
+ IndexConstraints map[string]*FieldStatsConstraints `json:"index_constraints,omitempty"`
+}
+
+// FieldStatsConstraints is a constraint on a field.
+type FieldStatsConstraints struct {
+ Min *FieldStatsComparison `json:"min_value,omitempty"`
+ Max *FieldStatsComparison `json:"max_value,omitempty"`
+}
+
+// FieldStatsComparison contain all comparison operations that can be used
+// in FieldStatsConstraints.
+type FieldStatsComparison struct {
+ Lte interface{} `json:"lte,omitempty"`
+ Lt interface{} `json:"lt,omitempty"`
+ Gte interface{} `json:"gte,omitempty"`
+ Gt interface{} `json:"gt,omitempty"`
+}
+
+// -- Response --
+
+// FieldStatsResponse is the response body content
+type FieldStatsResponse struct {
+ Indices map[string]IndexFieldStats `json:"indices,omitempty"`
+}
+
+// IndexFieldStats contains field stats for an index
+type IndexFieldStats struct {
+ Fields map[string]FieldStats `json:"fields,omitempty"`
+}
+
+// FieldStats contains stats of an individual field
+type FieldStats struct {
+ Type string `json:"type"`
+ MaxDoc int64 `json:"max_doc"`
+ DocCount int64 `json:"doc_count"`
+ Density int64 `json:"density"`
+ SumDocFrequeny int64 `json:"sum_doc_freq"`
+ SumTotalTermFrequency int64 `json:"sum_total_term_freq"`
+ Searchable bool `json:"searchable"`
+ Aggregatable bool `json:"aggregatable"`
+ MinValue interface{} `json:"min_value"`
+ MinValueAsString string `json:"min_value_as_string"`
+ MaxValue interface{} `json:"max_value"`
+ MaxValueAsString string `json:"max_value_as_string"`
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/geo_point_test.go b/vendor/gopkg.in/olivere/elastic.v5/geo_point_test.go
deleted file mode 100644
index 1d085cd38..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/geo_point_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoPointSource(t *testing.T) {
- pt := GeoPoint{Lat: 40, Lon: -70}
-
- data, err := json.Marshal(pt.Source())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"lat":40,"lon":-70}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/get.go b/vendor/gopkg.in/olivere/elastic.v5/get.go
index efcc748bb..ef569e174 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/get.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/get.go
@@ -11,13 +11,13 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// GetService allows to get a typed JSON document from the index based
// on its id.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-get.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-get.html
// for details.
type GetService struct {
client *Client
@@ -172,7 +172,7 @@ func (s *GetService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.routing != "" {
params.Set("routing", s.routing)
@@ -223,11 +223,7 @@ func (s *GetService) Do(ctx context.Context) (*GetResult, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/get_template.go b/vendor/gopkg.in/olivere/elastic.v5/get_template.go
new file mode 100644
index 000000000..93279a3a7
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/get_template.go
@@ -0,0 +1,113 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// GetTemplateService reads a search template.
+// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-template.html.
+type GetTemplateService struct {
+ client *Client
+ pretty bool
+ id string
+ version interface{}
+ versionType string
+}
+
+// NewGetTemplateService creates a new GetTemplateService.
+func NewGetTemplateService(client *Client) *GetTemplateService {
+ return &GetTemplateService{
+ client: client,
+ }
+}
+
+// Id is the template ID.
+func (s *GetTemplateService) Id(id string) *GetTemplateService {
+ s.id = id
+ return s
+}
+
+// Version is an explicit version number for concurrency control.
+func (s *GetTemplateService) Version(version interface{}) *GetTemplateService {
+ s.version = version
+ return s
+}
+
+// VersionType is a specific version type.
+func (s *GetTemplateService) VersionType(versionType string) *GetTemplateService {
+ s.versionType = versionType
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *GetTemplateService) buildURL() (string, url.Values, error) {
+ // Build URL
+ path, err := uritemplates.Expand("/_search/template/{id}", map[string]string{
+ "id": s.id,
+ })
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.version != nil {
+ params.Set("version", fmt.Sprintf("%v", s.version))
+ }
+ if s.versionType != "" {
+ params.Set("version_type", s.versionType)
+ }
+
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *GetTemplateService) Validate() error {
+ var invalid []string
+ if s.id == "" {
+ invalid = append(invalid, "Id")
+ }
+ if len(invalid) > 0 {
+ return fmt.Errorf("missing required fields: %v", invalid)
+ }
+ return nil
+}
+
+// Do executes the operation and returns the template.
+func (s *GetTemplateService) Do(ctx context.Context) (*GetTemplateResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return result
+ ret := new(GetTemplateResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+type GetTemplateResponse struct {
+ Template string `json:"template"`
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/get_test.go b/vendor/gopkg.in/olivere/elastic.v5/get_test.go
deleted file mode 100644
index f9504bdbf..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/get_test.go
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestGet(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Get document 1
- res, err := client.Get().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Found != true {
- t.Errorf("expected Found = true; got %v", res.Found)
- }
- if res.Source == nil {
- t.Errorf("expected Source != nil; got %v", res.Source)
- }
-
- // Get non existent document 99
- res, err = client.Get().Index(testIndexName).Type("doc").Id("99").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected error; got: %v", err)
- }
- if !IsNotFound(err) {
- t.Errorf("expected NotFound error; got: %v", err)
- }
- if res != nil {
- t.Errorf("expected no response; got: %v", res)
- }
-}
-
-func TestGetWithSourceFiltering(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Get document 1, without source
- res, err := client.Get().Index(testIndexName).Type("doc").Id("1").FetchSource(false).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Found != true {
- t.Errorf("expected Found = true; got %v", res.Found)
- }
- if res.Source != nil {
- t.Errorf("expected Source == nil; got %v", res.Source)
- }
-
- // Get document 1, exclude Message field
- fsc := NewFetchSourceContext(true).Exclude("message")
- res, err = client.Get().Index(testIndexName).Type("doc").Id("1").FetchSourceContext(fsc).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Found != true {
- t.Errorf("expected Found = true; got %v", res.Found)
- }
- if res.Source == nil {
- t.Errorf("expected Source != nil; got %v", res.Source)
- }
- var tw tweet
- err = json.Unmarshal(*res.Source, &tw)
- if err != nil {
- t.Fatal(err)
- }
- if tw.User != "olivere" {
- t.Errorf("expected user %q; got: %q", "olivere", tw.User)
- }
- if tw.Message != "" {
- t.Errorf("expected message %q; got: %q", "", tw.Message)
- }
-}
-
-func TestGetWithFields(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Get document 1, specifying fields
- res, err := client.Get().Index(testIndexName).Type("doc").Id("1").StoredFields("message").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Found != true {
- t.Errorf("expected Found = true; got: %v", res.Found)
- }
-
- // We must NOT have the "user" field
- _, ok := res.Fields["user"]
- if ok {
- t.Fatalf("expected no field %q in document", "user")
- }
-
- // We must have the "message" field
- messageField, ok := res.Fields["message"]
- if !ok {
- t.Fatalf("expected field %q in document", "message")
- }
-
- // Depending on the version of elasticsearch the message field will be returned
- // as a string or a slice of strings. This test works in both cases.
-
- messageString, ok := messageField.(string)
- if !ok {
- messageArray, ok := messageField.([]interface{})
- if !ok {
- t.Fatalf("expected field %q to be a string or a slice of strings; got: %T", "message", messageField)
- } else {
- messageString, ok = messageArray[0].(string)
- if !ok {
- t.Fatalf("expected field %q to be a string or a slice of strings; got: %T", "message", messageField)
- }
- }
- }
-
- if messageString != tweet1.Message {
- t.Errorf("expected message %q; got: %q", tweet1.Message, messageString)
- }
-}
-
-func TestGetValidate(t *testing.T) {
- // Mitigate against http://stackoverflow.com/questions/27491738/elasticsearch-go-index-failures-no-feature-for-name
- client := setupTestClientAndCreateIndex(t)
-
- if _, err := client.Get().Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
- if _, err := client.Get().Index(testIndexName).Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
- if _, err := client.Get().Type("doc").Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
- if _, err := client.Get().Id("1").Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
- if _, err := client.Get().Index(testIndexName).Type("doc").Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
- if _, err := client.Get().Type("doc").Id("1").Do(context.TODO()); err == nil {
- t.Fatal("expected Get to fail")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/highlight.go b/vendor/gopkg.in/olivere/elastic.v5/highlight.go
index 6d8d2ba63..478ff1d67 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/highlight.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/highlight.go
@@ -6,7 +6,7 @@ package elastic
// Highlight allows highlighting search results on one or more fields.
// For details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-highlighting.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-highlighting.html
type Highlight struct {
fields []*HighlighterField
tagsSchema *string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/highlight_test.go b/vendor/gopkg.in/olivere/elastic.v5/highlight_test.go
deleted file mode 100644
index c7b972c44..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/highlight_test.go
+++ /dev/null
@@ -1,211 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestHighlighterField(t *testing.T) {
- field := NewHighlighterField("grade")
- src, err := field.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlighterFieldWithOptions(t *testing.T) {
- field := NewHighlighterField("grade").FragmentSize(2).NumOfFragments(1)
- src, err := field.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fragment_size":2,"number_of_fragments":1}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlightWithStringField(t *testing.T) {
- builder := NewHighlight().Field("grade")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fields":{"grade":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlightWithFields(t *testing.T) {
- gradeField := NewHighlighterField("grade")
- builder := NewHighlight().Fields(gradeField)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fields":{"grade":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlightWithMultipleFields(t *testing.T) {
- gradeField := NewHighlighterField("grade")
- colorField := NewHighlighterField("color")
- builder := NewHighlight().Fields(gradeField, colorField)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fields":{"color":{},"grade":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlighterWithExplicitFieldOrder(t *testing.T) {
- gradeField := NewHighlighterField("grade").FragmentSize(2)
- colorField := NewHighlighterField("color").FragmentSize(2).NumOfFragments(1)
- builder := NewHighlight().Fields(gradeField, colorField).UseExplicitFieldOrder(true)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fields":[{"grade":{"fragment_size":2}},{"color":{"fragment_size":2,"number_of_fragments":1}}]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlightWithBoundarySettings(t *testing.T) {
- builder := NewHighlight().
- BoundaryChars(" \t\r").
- BoundaryScannerType("word")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"boundary_chars":" \t\r","boundary_scanner":"word"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHighlightWithTermQuery(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun to do."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Specify highlighter
- hl := NewHighlight()
- hl = hl.Fields(NewHighlighterField("message"))
- hl = hl.PreTags("<em>").PostTags("</em>")
-
- // Match all should return all documents
- query := NewPrefixQuery("message", "golang")
- searchResult, err := client.Search().
- Index(testIndexName).
- Highlight(hl).
- Query(query).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Fatalf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 1 {
- t.Fatalf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 1 {
- t.Fatalf("expected len(SearchResult.Hits.Hits) = %d; got %d", 1, len(searchResult.Hits.Hits))
- }
-
- hit := searchResult.Hits.Hits[0]
- var tw tweet
- if err := json.Unmarshal(*hit.Source, &tw); err != nil {
- t.Fatal(err)
- }
- if hit.Highlight == nil || len(hit.Highlight) == 0 {
- t.Fatal("expected hit to have a highlight; got nil")
- }
- if hl, found := hit.Highlight["message"]; found {
- if len(hl) != 1 {
- t.Fatalf("expected to have one highlight for field \"message\"; got %d", len(hl))
- }
- expected := "Welcome to <em>Golang</em> and Elasticsearch."
- if hl[0] != expected {
- t.Errorf("expected to have highlight \"%s\"; got \"%s\"", expected, hl[0])
- }
- } else {
- t.Fatal("expected to have a highlight on field \"message\"; got none")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/index.go b/vendor/gopkg.in/olivere/elastic.v5/index.go
index 4a4c3278e..302e0cdb6 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/index.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/index.go
@@ -9,13 +9,13 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndexService adds or updates a typed JSON document in a specified index,
// making it searchable.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-index_.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html
// for details.
type IndexService struct {
client *Client
@@ -172,7 +172,7 @@ func (s *IndexService) buildURL() (string, string, url.Values, error) {
})
} else {
// Automatic ID generation
- // See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-index_.html#index-creation
+ // See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#index-creation
method = "POST"
path, err = uritemplates.Expand("/{index}/{type}/", map[string]string{
"index": s.index,
@@ -186,7 +186,7 @@ func (s *IndexService) buildURL() (string, string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.waitForActiveShards != "" {
params.Set("wait_for_active_shards", s.waitForActiveShards)
@@ -264,12 +264,7 @@ func (s *IndexService) Do(ctx context.Context) (*IndexResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: method,
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, method, path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/index_test.go b/vendor/gopkg.in/olivere/elastic.v5/index_test.go
deleted file mode 100644
index 1a0c38576..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/index_test.go
+++ /dev/null
@@ -1,280 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestIndexLifecycle(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // Add a document
- indexResult, err := client.Index().
- Index(testIndexName).
- Type("doc").
- Id("1").
- BodyJson(&tweet1).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexResult == nil {
- t.Errorf("expected result to be != nil; got: %v", indexResult)
- }
-
- // Exists
- exists, err := client.Exists().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Errorf("expected exists %v; got %v", true, exists)
- }
-
- // Get document
- getResult, err := client.Get().
- Index(testIndexName).
- Type("doc").
- Id("1").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if getResult.Index != testIndexName {
- t.Errorf("expected GetResult.Index %q; got %q", testIndexName, getResult.Index)
- }
- if getResult.Type != "doc" {
- t.Errorf("expected GetResult.Type %q; got %q", "doc", getResult.Type)
- }
- if getResult.Id != "1" {
- t.Errorf("expected GetResult.Id %q; got %q", "1", getResult.Id)
- }
- if getResult.Source == nil {
- t.Errorf("expected GetResult.Source to be != nil; got nil")
- }
-
- // Decode the Source field
- var tweetGot tweet
- err = json.Unmarshal(*getResult.Source, &tweetGot)
- if err != nil {
- t.Fatal(err)
- }
- if tweetGot.User != tweet1.User {
- t.Errorf("expected Tweet.User to be %q; got %q", tweet1.User, tweetGot.User)
- }
- if tweetGot.Message != tweet1.Message {
- t.Errorf("expected Tweet.Message to be %q; got %q", tweet1.Message, tweetGot.Message)
- }
-
- // Delete document again
- deleteResult, err := client.Delete().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if deleteResult == nil {
- t.Errorf("expected result to be != nil; got: %v", deleteResult)
- }
-
- // Exists
- exists, err = client.Exists().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if exists {
- t.Errorf("expected exists %v; got %v", false, exists)
- }
-}
-
-func TestIndexLifecycleWithAutomaticIDGeneration(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // Add a document
- indexResult, err := client.Index().
- Index(testIndexName).
- Type("doc").
- BodyJson(&tweet1).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexResult == nil {
- t.Errorf("expected result to be != nil; got: %v", indexResult)
- }
- if indexResult.Id == "" {
- t.Fatalf("expected Es to generate an automatic ID, got: %v", indexResult.Id)
- }
- id := indexResult.Id
-
- // Exists
- exists, err := client.Exists().Index(testIndexName).Type("doc").Id(id).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Errorf("expected exists %v; got %v", true, exists)
- }
-
- // Get document
- getResult, err := client.Get().
- Index(testIndexName).
- Type("doc").
- Id(id).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if getResult.Index != testIndexName {
- t.Errorf("expected GetResult.Index %q; got %q", testIndexName, getResult.Index)
- }
- if getResult.Type != "doc" {
- t.Errorf("expected GetResult.Type %q; got %q", "doc", getResult.Type)
- }
- if getResult.Id != id {
- t.Errorf("expected GetResult.Id %q; got %q", id, getResult.Id)
- }
- if getResult.Source == nil {
- t.Errorf("expected GetResult.Source to be != nil; got nil")
- }
-
- // Decode the Source field
- var tweetGot tweet
- err = json.Unmarshal(*getResult.Source, &tweetGot)
- if err != nil {
- t.Fatal(err)
- }
- if tweetGot.User != tweet1.User {
- t.Errorf("expected Tweet.User to be %q; got %q", tweet1.User, tweetGot.User)
- }
- if tweetGot.Message != tweet1.Message {
- t.Errorf("expected Tweet.Message to be %q; got %q", tweet1.Message, tweetGot.Message)
- }
-
- // Delete document again
- deleteResult, err := client.Delete().Index(testIndexName).Type("doc").Id(id).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if deleteResult == nil {
- t.Errorf("expected result to be != nil; got: %v", deleteResult)
- }
-
- // Exists
- exists, err = client.Exists().Index(testIndexName).Type("doc").Id(id).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if exists {
- t.Errorf("expected exists %v; got %v", false, exists)
- }
-}
-
-func TestIndexValidate(t *testing.T) {
- client := setupTestClient(t)
-
- tweet := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // No index name -> fail with error
- res, err := NewIndexService(client).Type("doc").Id("1").BodyJson(&tweet).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Index to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-
- // No index name -> fail with error
- res, err = NewIndexService(client).Index(testIndexName).Id("1").BodyJson(&tweet).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected Index to fail without type")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
-
-func TestIndexCreateExistsOpenCloseDelete(t *testing.T) {
- // TODO: Find out how to make these test robust
- t.Skip("test fails regularly with 409 (Conflict): " +
- "IndexPrimaryShardNotAllocatedException[[elastic-test] " +
- "primary not allocated post api... skipping")
-
- client := setupTestClient(t)
-
- // Create index
- createIndex, err := client.CreateIndex(testIndexName).Body(testMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Fatalf("expected response; got: %v", createIndex)
- }
- if !createIndex.Acknowledged {
- t.Errorf("expected ack for creating index; got: %v", createIndex.Acknowledged)
- }
-
- // Exists
- indexExists, err := client.IndexExists(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !indexExists {
- t.Fatalf("expected index exists=%v; got %v", true, indexExists)
- }
-
- // Flush
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Close index
- closeIndex, err := client.CloseIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if closeIndex == nil {
- t.Fatalf("expected response; got: %v", closeIndex)
- }
- if !closeIndex.Acknowledged {
- t.Errorf("expected ack for closing index; got: %v", closeIndex.Acknowledged)
- }
-
- // Open index
- openIndex, err := client.OpenIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if openIndex == nil {
- t.Fatalf("expected response; got: %v", openIndex)
- }
- if !openIndex.Acknowledged {
- t.Errorf("expected ack for opening index; got: %v", openIndex.Acknowledged)
- }
-
- // Flush
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Delete index
- deleteIndex, err := client.DeleteIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if deleteIndex == nil {
- t.Fatalf("expected response; got: %v", deleteIndex)
- }
- if !deleteIndex.Acknowledged {
- t.Errorf("expected ack for deleting index; got %v", deleteIndex.Acknowledged)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_analyze.go b/vendor/gopkg.in/olivere/elastic.v5/indices_analyze.go
index fb3a91234..b9000f128 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_analyze.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_analyze.go
@@ -9,13 +9,13 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesAnalyzeService performs the analysis process on a text and returns
// the tokens breakdown of the text.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-analyze.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-analyze.html
// for detail.
type IndicesAnalyzeService struct {
client *Client
@@ -152,7 +152,7 @@ func (s *IndicesAnalyzeService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.format != "" {
params.Set("format", s.format)
@@ -185,16 +185,11 @@ func (s *IndicesAnalyzeService) Do(ctx context.Context) (*IndicesAnalyzeResponse
} else {
// Request parameters are deprecated in 5.1.1, and we must use a JSON
// structure in the body to pass the parameters.
- // See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-analyze.html
+ // See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-analyze.html
body = s.request
}
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_analyze_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_analyze_test.go
deleted file mode 100644
index 90dbf1e73..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_analyze_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesAnalyzeURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Index string
- Expected string
- }{
- {
- "",
- "/_analyze",
- },
- {
- "tweets",
- "/tweets/_analyze",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IndexAnalyze().Index(test.Index).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestIndicesAnalyze(t *testing.T) {
- client := setupTestClient(t)
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- res, err := client.IndexAnalyze().Text("hello hi guy").Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error, got %v", err)
- }
- if len(res.Tokens) != 3 {
- t.Fatalf("expected %d, got %d (%+v)", 3, len(res.Tokens), res.Tokens)
- }
-}
-
-func TestIndicesAnalyzeDetail(t *testing.T) {
- client := setupTestClient(t)
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- res, err := client.IndexAnalyze().Text("hello hi guy").Explain(true).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error, got %v", err)
- }
-
- if len(res.Detail.Analyzer.Tokens) != 3 {
- t.Fatalf("expected %d tokens, got %d (%+v)", 3, len(res.Detail.Tokenizer.Tokens), res.Detail.Tokenizer.Tokens)
- }
-}
-
-func TestIndicesAnalyzeWithIndex(t *testing.T) {
- client := setupTestClient(t)
-
- _, err := client.IndexAnalyze().Index("foo").Text("hello hi guy").Do(context.TODO())
- if err == nil {
- t.Fatal("expected error, got nil")
- }
- if want, have := "elastic: Error 404 (Not Found): no such index [type=index_not_found_exception]", err.Error(); want != have {
- t.Fatalf("expected error %q, got %q", want, have)
- }
-}
-
-func TestIndicesAnalyzeValidate(t *testing.T) {
- client := setupTestClient(t)
-
- _, err := client.IndexAnalyze().Do(context.TODO())
- if err == nil {
- t.Fatal("expected error, got nil")
- }
- if want, have := "missing required fields: [Text]", err.Error(); want != have {
- t.Fatalf("expected error %q, got %q", want, have)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_close.go b/vendor/gopkg.in/olivere/elastic.v5/indices_close.go
index 00ecdf966..9388bc973 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_close.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_close.go
@@ -9,12 +9,12 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesCloseService closes an index.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-open-close.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-open-close.html
// for details.
type IndicesCloseService struct {
client *Client
@@ -134,11 +134,7 @@ func (s *IndicesCloseService) Do(ctx context.Context) (*IndicesCloseResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
@@ -153,7 +149,5 @@ func (s *IndicesCloseService) Do(ctx context.Context) (*IndicesCloseResponse, er
// IndicesCloseResponse is the response of IndicesCloseService.Do.
type IndicesCloseResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_close_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_close_test.go
deleted file mode 100644
index e7a4d9e05..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_close_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-// TODO(oe): Find out why this test fails on Travis CI.
-/*
-func TestIndicesOpenAndClose(t *testing.T) {
- client := setupTestClient(t)
-
- // Create index
- createIndex, err := client.CreateIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !createIndex.Acknowledged {
- t.Errorf("expected CreateIndexResult.Acknowledged %v; got %v", true, createIndex.Acknowledged)
- }
- defer func() {
- // Delete index
- deleteIndex, err := client.DeleteIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !deleteIndex.Acknowledged {
- t.Errorf("expected DeleteIndexResult.Acknowledged %v; got %v", true, deleteIndex.Acknowledged)
- }
- }()
-
- waitForYellow := func() {
- // Wait for status yellow
- res, err := client.ClusterHealth().WaitForStatus("yellow").Timeout("15s").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res != nil && res.TimedOut {
- t.Fatalf("cluster time out waiting for status %q", "yellow")
- }
- }
-
- // Wait for cluster
- waitForYellow()
-
- // Close index
- cresp, err := client.CloseIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !cresp.Acknowledged {
- t.Fatalf("expected close index of %q to be acknowledged\n", testIndexName)
- }
-
- // Wait for cluster
- waitForYellow()
-
- // Open index again
- oresp, err := client.OpenIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !oresp.Acknowledged {
- t.Fatalf("expected open index of %q to be acknowledged\n", testIndexName)
- }
-}
-*/
-
-func TestIndicesCloseValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesCloseService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesClose to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_create.go b/vendor/gopkg.in/olivere/elastic.v5/indices_create.go
index 8d8e0c25e..dfd17ac09 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_create.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_create.go
@@ -9,12 +9,12 @@ import (
"errors"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesCreateService creates a new index.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-create-index.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-create-index.html
// for details.
type IndicesCreateService struct {
client *Client
@@ -91,7 +91,7 @@ func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, er
params := make(url.Values)
if b.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if b.masterTimeout != "" {
params.Set("master_timeout", b.masterTimeout)
@@ -109,12 +109,7 @@ func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, er
}
// Get response
- res, err := b.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := b.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -130,7 +125,6 @@ func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, er
// IndicesCreateResult is the outcome of creating a new index.
type IndicesCreateResult struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
+ ShardsAcknowledged bool `json:"shards_acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_create_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_create_test.go
deleted file mode 100644
index f37df1c54..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_create_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesLifecycle(t *testing.T) {
- client := setupTestClient(t)
-
- // Create index
- createIndex, err := client.CreateIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !createIndex.Acknowledged {
- t.Errorf("expected IndicesCreateResult.Acknowledged %v; got %v", true, createIndex.Acknowledged)
- }
-
- // Check if index exists
- indexExists, err := client.IndexExists(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !indexExists {
- t.Fatalf("index %s should exist, but doesn't\n", testIndexName)
- }
-
- // Delete index
- deleteIndex, err := client.DeleteIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !deleteIndex.Acknowledged {
- t.Errorf("expected DeleteIndexResult.Acknowledged %v; got %v", true, deleteIndex.Acknowledged)
- }
-
- // Check if index exists
- indexExists, err = client.IndexExists(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexExists {
- t.Fatalf("index %s should not exist, but does\n", testIndexName)
- }
-}
-
-func TestIndicesCreateValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesCreateService(client).Body(testMapping).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesCreate to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_delete.go b/vendor/gopkg.in/olivere/elastic.v5/indices_delete.go
index 2afeca978..997185237 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_delete.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_delete.go
@@ -10,12 +10,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesDeleteService allows to delete existing indices.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-delete-index.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-delete-index.html
// for details.
type IndicesDeleteService struct {
client *Client
@@ -71,7 +71,7 @@ func (s *IndicesDeleteService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.timeout != "" {
params.Set("timeout", s.timeout)
@@ -108,11 +108,7 @@ func (s *IndicesDeleteService) Do(ctx context.Context) (*IndicesDeleteResponse,
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_delete_template.go b/vendor/gopkg.in/olivere/elastic.v5/indices_delete_template.go
index 0ea34cf89..d1b88d4bb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_delete_template.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_delete_template.go
@@ -9,11 +9,11 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesDeleteTemplateService deletes index templates.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-templates.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-templates.html.
type IndicesDeleteTemplateService struct {
client *Client
pretty bool
@@ -66,7 +66,7 @@ func (s *IndicesDeleteTemplateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.timeout != "" {
params.Set("timeout", s.timeout)
@@ -103,11 +103,7 @@ func (s *IndicesDeleteTemplateService) Do(ctx context.Context) (*IndicesDeleteTe
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
if err != nil {
return nil, err
}
@@ -122,7 +118,5 @@ func (s *IndicesDeleteTemplateService) Do(ctx context.Context) (*IndicesDeleteTe
// IndicesDeleteTemplateResponse is the response of IndicesDeleteTemplateService.Do.
type IndicesDeleteTemplateResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged,omitempty"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_delete_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_delete_test.go
deleted file mode 100644
index db77c7a25..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_delete_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesDeleteValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesDeleteService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesDelete to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists.go
index aa9391039..928006e09 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_exists.go
@@ -11,12 +11,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesExistsService checks if an index or indices exist or not.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-exists.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-exists.html
// for details.
type IndicesExistsService struct {
client *Client
@@ -90,7 +90,7 @@ func (s *IndicesExistsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.local != nil {
params.Set("local", fmt.Sprintf("%v", *s.local))
@@ -133,12 +133,7 @@ func (s *IndicesExistsService) Do(ctx context.Context) (bool, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "HEAD",
- Path: path,
- Params: params,
- IgnoreErrors: []int{404},
- })
+ res, err := s.client.PerformRequest(ctx, "HEAD", path, params, nil, 404)
if err != nil {
return false, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template.go
index 40b06e895..873d8c00c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template.go
@@ -10,7 +10,7 @@ import (
"net/http"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesExistsTemplateService checks if a given template exists.
@@ -62,7 +62,7 @@ func (s *IndicesExistsTemplateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.local != nil {
params.Set("local", fmt.Sprintf("%v", *s.local))
@@ -96,12 +96,7 @@ func (s *IndicesExistsTemplateService) Do(ctx context.Context) (bool, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "HEAD",
- Path: path,
- Params: params,
- IgnoreErrors: []int{404},
- })
+ res, err := s.client.PerformRequest(ctx, "HEAD", path, params, nil, 404)
if err != nil {
return false, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template_test.go
deleted file mode 100644
index a97442971..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_template_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndexExistsTemplate(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tmpl := `{
- "index_patterns":["elastic-test*"],
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "tags":{
- "type":"keyword"
- },
- "location":{
- "type":"geo_point"
- },
- "suggest_field":{
- "type":"completion"
- }
- }
- }
- }
-}`
- putres, err := client.IndexPutTemplate("elastic-template").BodyString(tmpl).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if putres == nil {
- t.Fatalf("expected response; got: %v", putres)
- }
- if !putres.Acknowledged {
- t.Fatalf("expected index template to be ack'd; got: %v", putres.Acknowledged)
- }
-
- // Always delete template
- defer client.IndexDeleteTemplate("elastic-template").Do(context.TODO())
-
- // Check if template exists
- exists, err := client.IndexTemplateExists("elastic-template").Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if !exists {
- t.Fatalf("expected index template %q to exist; got: %v", "elastic-template", exists)
- }
-
- // Get template
- getres, err := client.IndexGetTemplate("elastic-template").Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if getres == nil {
- t.Fatalf("expected to get index template %q; got: %v", "elastic-template", getres)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_test.go
deleted file mode 100644
index 07e3eb518..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesExistsWithoutIndex(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesExistsService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesExists to fail without index name")
- }
- if res != false {
- t.Fatalf("expected result to be false; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type.go
index a4d1ff610..95eb8f1d3 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type.go
@@ -11,12 +11,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesExistsTypeService checks if one or more types exist in one or more indices.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-types-exists.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-types-exists.html
// for details.
type IndicesExistsTypeService struct {
client *Client
@@ -97,7 +97,7 @@ func (s *IndicesExistsTypeService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
@@ -143,12 +143,7 @@ func (s *IndicesExistsTypeService) Do(ctx context.Context) (bool, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "HEAD",
- Path: path,
- Params: params,
- IgnoreErrors: []int{404},
- })
+ res, err := s.client.PerformRequest(ctx, "HEAD", path, params, nil, 404)
if err != nil {
return false, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type_test.go
deleted file mode 100644
index 3795bd042..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_exists_type_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesExistsTypeBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- ExpectValidateFailure bool
- }{
- {
- []string{},
- []string{},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{},
- "",
- true,
- },
- {
- []string{},
- []string{"type1"},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{"type1"},
- "/index1/_mapping/type1",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{"type1"},
- "/index1%2Cindex2/_mapping/type1",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{"type1", "type2"},
- "/index1%2Cindex2/_mapping/type1%2Ctype2",
- false,
- },
- }
-
- for i, test := range tests {
- err := client.TypeExists().Index(test.Indices...).Type(test.Types...).Validate()
- if err == nil && test.ExpectValidateFailure {
- t.Errorf("#%d: expected validate to fail", i+1)
- continue
- }
- if err != nil && !test.ExpectValidateFailure {
- t.Errorf("#%d: expected validate to succeed", i+1)
- continue
- }
- if !test.ExpectValidateFailure {
- path, _, err := client.TypeExists().Index(test.Indices...).Type(test.Types...).buildURL()
- if err != nil {
- t.Fatalf("#%d: %v", i+1, err)
- }
- if path != test.Expected {
- t.Errorf("#%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
- }
-}
-
-func TestIndicesExistsType(t *testing.T) {
- client := setupTestClient(t)
-
- // Create index with tweet type
- createIndex, err := client.CreateIndex(testIndexName).Body(testMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex)
- }
- if !createIndex.Acknowledged {
- t.Errorf("expected CreateIndexResult.Acknowledged %v; got %v", true, createIndex.Acknowledged)
- }
-
- // Check if type exists
- exists, err := client.TypeExists().Index(testIndexName).Type("doc").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !exists {
- t.Fatalf("type %s should exist in index %s, but doesn't\n", "doc", testIndexName)
- }
-
- // Delete index
- deleteIndex, err := client.DeleteIndex(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !deleteIndex.Acknowledged {
- t.Errorf("expected DeleteIndexResult.Acknowledged %v; got %v", true, deleteIndex.Acknowledged)
- }
-
- // Check if type exists
- exists, err = client.TypeExists().Index(testIndexName).Type("doc").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if exists {
- t.Fatalf("type %s should not exist in index %s, but it does\n", "doc", testIndexName)
- }
-}
-
-func TestIndicesExistsTypeValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesExistsTypeService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesExistsType to fail without index name")
- }
- if res != false {
- t.Fatalf("expected result to be false; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_flush.go b/vendor/gopkg.in/olivere/elastic.v5/indices_flush.go
index 113e53803..602700af6 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_flush.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_flush.go
@@ -10,14 +10,14 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// Flush allows to flush one or more indices. The flush process of an index
// basically frees memory from the index by flushing data to the index
// storage and clearing the internal transaction log.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-flush.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-flush.html
// for details.
type IndicesFlushService struct {
client *Client
@@ -110,7 +110,7 @@ func (s *IndicesFlushService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.force != nil {
params.Set("force", fmt.Sprintf("%v", *s.force))
@@ -149,11 +149,7 @@ func (s *IndicesFlushService) Do(ctx context.Context) (*IndicesFlushResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_flush_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_flush_test.go
deleted file mode 100644
index afefd1251..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_flush_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestFlush(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Flush all indices
- res, err := client.Flush().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Errorf("expected res to be != nil; got: %v", res)
- }
-}
-
-func TestFlushBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Expected string
- ExpectValidateFailure bool
- }{
- {
- []string{},
- "/_flush",
- false,
- },
- {
- []string{"index1"},
- "/index1/_flush",
- false,
- },
- {
- []string{"index1", "index2"},
- "/index1%2Cindex2/_flush",
- false,
- },
- }
-
- for i, test := range tests {
- err := NewIndicesFlushService(client).Index(test.Indices...).Validate()
- if err == nil && test.ExpectValidateFailure {
- t.Errorf("case #%d: expected validate to fail", i+1)
- continue
- }
- if err != nil && !test.ExpectValidateFailure {
- t.Errorf("case #%d: expected validate to succeed", i+1)
- continue
- }
- if !test.ExpectValidateFailure {
- path, _, err := NewIndicesFlushService(client).Index(test.Indices...).buildURL()
- if err != nil {
- t.Fatalf("case #%d: %v", i+1, err)
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge.go b/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge.go
index 0e999cf19..709be1bc4 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge.go
@@ -10,7 +10,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesForcemergeService allows to force merging of one or more indices.
@@ -125,7 +125,7 @@ func (s *IndicesForcemergeService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
@@ -170,11 +170,7 @@ func (s *IndicesForcemergeService) Do(ctx context.Context) (*IndicesForcemergeRe
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge_test.go
deleted file mode 100644
index 6615d4dc6..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_forcemerge_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesForcemergeBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Expected string
- }{
- {
- []string{},
- "/_forcemerge",
- },
- {
- []string{"index1"},
- "/index1/_forcemerge",
- },
- {
- []string{"index1", "index2"},
- "/index1%2Cindex2/_forcemerge",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.Forcemerge().Index(test.Indices...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestIndicesForcemerge(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- _, err := client.Forcemerge(testIndexName).MaxNumSegments(1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- /*
- if !ok {
- t.Fatalf("expected forcemerge to succeed; got: %v", ok)
- }
- */
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get.go
index cb4e449d5..3b80c246d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get.go
@@ -10,12 +10,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesGetService retrieves information about one or more indices.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-get-index.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-get-index.html
// for more details.
type IndicesGetService struct {
client *Client
@@ -131,7 +131,7 @@ func (s *IndicesGetService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.expandWildcards != "" {
params.Set("expand_wildcards", s.expandWildcards)
@@ -180,11 +180,7 @@ func (s *IndicesGetService) Do(ctx context.Context) (map[string]*IndicesGetRespo
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases.go
index 68b186358..530d7bdcd 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases.go
@@ -10,7 +10,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// AliasesService returns the aliases associated with one or more indices.
@@ -47,11 +47,11 @@ func (s *AliasesService) buildURL() (string, url.Values, error) {
var path string
if len(s.index) > 0 {
- path, err = uritemplates.Expand("/{index}/_alias", map[string]string{
+ path, err = uritemplates.Expand("/{index}/_aliases", map[string]string{
"index": strings.Join(s.index, ","),
})
} else {
- path = "/_alias"
+ path = "/_aliases"
}
if err != nil {
return "", url.Values{}, err
@@ -72,11 +72,7 @@ func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error) {
}
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases_test.go
deleted file mode 100644
index 2c8da9b7f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_aliases_test.go
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestAliasesBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Expected string
- }{
- {
- []string{},
- "/_alias",
- },
- {
- []string{"index1"},
- "/index1/_alias",
- },
- {
- []string{"index1", "index2"},
- "/index1%2Cindex2/_alias",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.Aliases().Index(test.Indices...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestAliases(t *testing.T) {
- var err error
-
- //client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- // Some tweets
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Cycling is fun."}
- tweet3 := tweet{User: "olivere", Message: "Another unrelated topic."}
-
- // Add tweets to first index
- _, err = client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- // Add tweets to second index
- _, err = client.Index().Index(testIndexName2).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Flush
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Flush().Index(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Alias should not yet exist
- aliasesResult1, err := client.Aliases().
- Index(testIndexName, testIndexName2).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if len(aliasesResult1.Indices) != 2 {
- t.Errorf("expected len(AliasesResult.Indices) = %d; got %d", 2, len(aliasesResult1.Indices))
- }
- for indexName, indexDetails := range aliasesResult1.Indices {
- if len(indexDetails.Aliases) != 0 {
- t.Errorf("expected len(AliasesResult.Indices[%s].Aliases) = %d; got %d", indexName, 0, len(indexDetails.Aliases))
- }
- }
-
- // Add both indices to a new alias
- aliasCreate, err := client.Alias().
- Add(testIndexName, testAliasName).
- Add(testIndexName2, testAliasName).
- //Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !aliasCreate.Acknowledged {
- t.Errorf("expected AliasResult.Acknowledged %v; got %v", true, aliasCreate.Acknowledged)
- }
-
- // Alias should now exist
- aliasesResult2, err := client.Aliases().
- Index(testIndexName, testIndexName2).
- //Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if len(aliasesResult2.Indices) != 2 {
- t.Errorf("expected len(AliasesResult.Indices) = %d; got %d", 2, len(aliasesResult2.Indices))
- }
- for indexName, indexDetails := range aliasesResult2.Indices {
- if len(indexDetails.Aliases) != 1 {
- t.Errorf("expected len(AliasesResult.Indices[%s].Aliases) = %d; got %d", indexName, 1, len(indexDetails.Aliases))
- }
- }
-
- // Check the reverse function:
- indexInfo1, found := aliasesResult2.Indices[testIndexName]
- if !found {
- t.Errorf("expected info about index %s = %v; got %v", testIndexName, true, found)
- }
- aliasFound := indexInfo1.HasAlias(testAliasName)
- if !aliasFound {
- t.Errorf("expected alias %s to include index %s; got %v", testAliasName, testIndexName, aliasFound)
- }
-
- // Check the reverse function:
- indexInfo2, found := aliasesResult2.Indices[testIndexName2]
- if !found {
- t.Errorf("expected info about index %s = %v; got %v", testIndexName, true, found)
- }
- aliasFound = indexInfo2.HasAlias(testAliasName)
- if !aliasFound {
- t.Errorf("expected alias %s to include index %s; got %v", testAliasName, testIndexName2, aliasFound)
- }
-
- // Remove first index should remove two tweets, so should only yield 1
- aliasRemove1, err := client.Alias().
- Remove(testIndexName, testAliasName).
- //Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !aliasRemove1.Acknowledged {
- t.Errorf("expected AliasResult.Acknowledged %v; got %v", true, aliasRemove1.Acknowledged)
- }
-
- // Alias should now exist only for index 2
- aliasesResult3, err := client.Aliases().Index(testIndexName, testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if len(aliasesResult3.Indices) != 2 {
- t.Errorf("expected len(AliasesResult.Indices) = %d; got %d", 2, len(aliasesResult3.Indices))
- }
- for indexName, indexDetails := range aliasesResult3.Indices {
- if indexName == testIndexName {
- if len(indexDetails.Aliases) != 0 {
- t.Errorf("expected len(AliasesResult.Indices[%s].Aliases) = %d; got %d", indexName, 0, len(indexDetails.Aliases))
- }
- } else if indexName == testIndexName2 {
- if len(indexDetails.Aliases) != 1 {
- t.Errorf("expected len(AliasesResult.Indices[%s].Aliases) = %d; got %d", indexName, 1, len(indexDetails.Aliases))
- }
- } else {
- t.Errorf("got index %s", indexName)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping.go
index e3b7eac07..3cb43d54b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping.go
@@ -10,13 +10,13 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesGetFieldMappingService retrieves the mapping definitions for the fields in an index
// or index/type.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-get-field-mapping.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-get-field-mapping.html
// for details.
type IndicesGetFieldMappingService struct {
client *Client
@@ -131,7 +131,7 @@ func (s *IndicesGetFieldMappingService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
@@ -170,11 +170,7 @@ func (s *IndicesGetFieldMappingService) Do(ctx context.Context) (map[string]inte
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping_test.go
deleted file mode 100644
index 62770e030..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_field_mapping_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestIndicesGetFieldMappingURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Fields []string
- Expected string
- }{
- {
- []string{},
- []string{},
- []string{},
- "/_all/_mapping/_all/field/%2A",
- },
- {
- []string{},
- []string{"tweet"},
- []string{"message"},
- "/_all/_mapping/tweet/field/message",
- },
- {
- []string{"twitter"},
- []string{"tweet"},
- []string{"*.id"},
- "/twitter/_mapping/tweet/field/%2A.id",
- },
- {
- []string{"store-1", "store-2"},
- []string{"tweet", "user"},
- []string{"message", "*.id"},
- "/store-1%2Cstore-2/_mapping/tweet%2Cuser/field/message%2C%2A.id",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.GetFieldMapping().Index(test.Indices...).Type(test.Types...).Field(test.Fields...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping.go
index 7f9c9cb22..3b2258915 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping.go
@@ -10,13 +10,13 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesGetMappingService retrieves the mapping definitions for an index or
// index/type.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-get-mapping.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-get-mapping.html
// for details.
type IndicesGetMappingService struct {
client *Client
@@ -119,7 +119,7 @@ func (s *IndicesGetMappingService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
@@ -156,11 +156,7 @@ func (s *IndicesGetMappingService) Do(ctx context.Context) (map[string]interface
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping_test.go
deleted file mode 100644
index 5ec54e7fb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_mapping_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestIndicesGetMappingURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_all/_mapping/_all",
- },
- {
- []string{},
- []string{"tweet"},
- "/_all/_mapping/tweet",
- },
- {
- []string{"twitter"},
- []string{"tweet"},
- "/twitter/_mapping/tweet",
- },
- {
- []string{"store-1", "store-2"},
- []string{"tweet", "user"},
- "/store-1%2Cstore-2/_mapping/tweet%2Cuser",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.GetMapping().Index(test.Indices...).Type(test.Types...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings.go
index 06fce0dfa..0e8f28d70 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings.go
@@ -10,13 +10,13 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesGetSettingsService allows to retrieve settings of one
// or more indices.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-get-settings.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-get-settings.html
// for more details.
type IndicesGetSettingsService struct {
client *Client
@@ -125,7 +125,7 @@ func (s *IndicesGetSettingsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
@@ -164,11 +164,7 @@ func (s *IndicesGetSettingsService) Do(ctx context.Context) (map[string]*Indices
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings_test.go
deleted file mode 100644
index 7c6995a28..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_settings_test.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndexGetSettingsURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Names []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_all/_settings",
- },
- {
- []string{},
- []string{"index.merge.*"},
- "/_all/_settings/index.merge.%2A",
- },
- {
- []string{"twitter-*"},
- []string{"index.merge.*", "_settings"},
- "/twitter-%2A/_settings/index.merge.%2A%2C_settings",
- },
- {
- []string{"store-1", "store-2"},
- []string{"index.merge.*", "_settings"},
- "/store-1%2Cstore-2/_settings/index.merge.%2A%2C_settings",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IndexGetSettings().Index(test.Indices...).Name(test.Names...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestIndexGetSettingsService(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "1.4.0" {
- t.Skip("Index Get API is available since 1.4")
- return
- }
-
- res, err := client.IndexGetSettings().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected result; got: %v", res)
- }
- info, found := res[testIndexName]
- if !found {
- t.Fatalf("expected index %q to be found; got: %v", testIndexName, found)
- }
- if info == nil {
- t.Fatalf("expected index %q to be != nil; got: %v", testIndexName, info)
- }
- if info.Settings == nil {
- t.Fatalf("expected index settings of %q to be != nil; got: %v", testIndexName, info.Settings)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_template.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_template.go
index ad3a091a0..15590dc06 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_template.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_get_template.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesGetTemplateService returns an index template.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-templates.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-templates.html.
type IndicesGetTemplateService struct {
client *Client
pretty bool
@@ -75,7 +75,7 @@ func (s *IndicesGetTemplateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.flatSettings != nil {
params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings))
@@ -105,11 +105,7 @@ func (s *IndicesGetTemplateService) Do(ctx context.Context) (map[string]*Indices
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_template_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_template_test.go
deleted file mode 100644
index c884ec1cb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_template_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestIndexGetTemplateURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Names []string
- Expected string
- }{
- {
- []string{},
- "/_template",
- },
- {
- []string{"index1"},
- "/_template/index1",
- },
- {
- []string{"index1", "index2"},
- "/_template/index1%2Cindex2",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IndexGetTemplate().Name(test.Names...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_get_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_get_test.go
deleted file mode 100644
index 6d37fca6e..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_get_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesGetValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesGetService(client).Index("").Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesGet to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
-
-func TestIndicesGetURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Features []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_all",
- },
- {
- []string{},
- []string{"_mappings"},
- "/_all/_mappings",
- },
- {
- []string{"twitter"},
- []string{"_mappings", "_settings"},
- "/twitter/_mappings%2C_settings",
- },
- {
- []string{"store-1", "store-2"},
- []string{"_mappings", "_settings"},
- "/store-1%2Cstore-2/_mappings%2C_settings",
- },
- }
-
- for _, test := range tests {
- path, _, err := NewIndicesGetService(client).Index(test.Indices...).Feature(test.Features...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestIndicesGetService(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "1.4.0" {
- t.Skip("Index Get API is available since 1.4")
- return
- }
-
- res, err := client.IndexGet().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("expected result; got: %v", res)
- }
- info, found := res[testIndexName]
- if !found {
- t.Fatalf("expected index %q to be found; got: %v", testIndexName, found)
- }
- if info == nil {
- t.Fatalf("expected index %q to be != nil; got: %v", testIndexName, info)
- }
- if info.Mappings == nil {
- t.Errorf("expected mappings to be != nil; got: %v", info.Mappings)
- }
- if info.Settings == nil {
- t.Errorf("expected settings to be != nil; got: %v", info.Settings)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_open.go b/vendor/gopkg.in/olivere/elastic.v5/indices_open.go
index 1b58c5721..38277c385 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_open.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_open.go
@@ -9,12 +9,12 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesOpenService opens an index.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-open-close.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-open-close.html
// for details.
type IndicesOpenService struct {
client *Client
@@ -91,7 +91,7 @@ func (s *IndicesOpenService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.timeout != "" {
params.Set("timeout", s.timeout)
@@ -138,11 +138,7 @@ func (s *IndicesOpenService) Do(ctx context.Context) (*IndicesOpenResponse, erro
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
@@ -157,7 +153,5 @@ func (s *IndicesOpenService) Do(ctx context.Context) (*IndicesOpenResponse, erro
// IndicesOpenResponse is the response of IndicesOpenService.Do.
type IndicesOpenResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_open_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_open_test.go
deleted file mode 100644
index aab6c5c19..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_open_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesOpenValidate(t *testing.T) {
- client := setupTestClient(t)
-
- // No index name -> fail with error
- res, err := NewIndicesOpenService(client).Do(context.TODO())
- if err == nil {
- t.Fatalf("expected IndicesOpen to fail without index name")
- }
- if res != nil {
- t.Fatalf("expected result to be == nil; got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias.go
index 12f8e1bd5..5d965bd66 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias.go
@@ -192,7 +192,7 @@ func (a *AliasRemoveAction) Source() (interface{}, error) {
// -- Service --
// AliasService enables users to add or remove an alias.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-aliases.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-aliases.html
// for details.
type AliasService struct {
client *Client
@@ -274,12 +274,7 @@ func (s *AliasService) Do(ctx context.Context) (*AliasResult, error) {
body["actions"] = actions
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -296,7 +291,5 @@ func (s *AliasService) Do(ctx context.Context) (*AliasResult, error) {
// AliasResult is the outcome of calling Do on AliasService.
type AliasResult struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias_test.go
deleted file mode 100644
index ada1dfdef..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_alias_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-const (
- testAliasName = "elastic-test-alias"
-)
-
-func TestAliasLifecycle(t *testing.T) {
- var err error
-
- client := setupTestClientAndCreateIndex(t)
-
- // Some tweets
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "sandrae", Message: "Cycling is fun."}
- tweet3 := tweet{User: "olivere", Message: "Another unrelated topic."}
-
- // Add tweets to first index
- _, err = client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Add tweets to second index
- _, err = client.Index().Index(testIndexName2).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Flush
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Flush().Index(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Add both indices to a new alias
- aliasCreate, err := client.Alias().
- Add(testIndexName, testAliasName).
- Action(NewAliasAddAction(testAliasName).Index(testIndexName2)).
- //Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !aliasCreate.Acknowledged {
- t.Errorf("expected AliasResult.Acknowledged %v; got %v", true, aliasCreate.Acknowledged)
- }
-
- // Search should return all 3 tweets
- matchAll := NewMatchAllQuery()
- searchResult1, err := client.Search().Index(testAliasName).Query(matchAll).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult1.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult1.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult1.Hits.TotalHits)
- }
-
- // Remove first index should remove two tweets, so should only yield 1
- aliasRemove1, err := client.Alias().
- Remove(testIndexName, testAliasName).
- //Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if !aliasRemove1.Acknowledged {
- t.Errorf("expected AliasResult.Acknowledged %v; got %v", true, aliasRemove1.Acknowledged)
- }
-
- searchResult2, err := client.Search().Index(testAliasName).Query(matchAll).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult2.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult2.Hits.TotalHits != 1 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult2.Hits.TotalHits)
- }
-}
-
-func TestAliasAddAction(t *testing.T) {
- var tests = []struct {
- Action *AliasAddAction
- Expected string
- Invalid bool
- }{
- {
- Action: NewAliasAddAction("").Index(""),
- Invalid: true,
- },
- {
- Action: NewAliasAddAction("alias1").Index(""),
- Invalid: true,
- },
- {
- Action: NewAliasAddAction("").Index("index1"),
- Invalid: true,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1"),
- Expected: `{"add":{"alias":"alias1","index":"index1"}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1", "index2"),
- Expected: `{"add":{"alias":"alias1","indices":["index1","index2"]}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1").Routing("routing1"),
- Expected: `{"add":{"alias":"alias1","index":"index1","routing":"routing1"}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1").Routing("routing1").IndexRouting("indexRouting1"),
- Expected: `{"add":{"alias":"alias1","index":"index1","index_routing":"indexRouting1","routing":"routing1"}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1").Routing("routing1").SearchRouting("searchRouting1"),
- Expected: `{"add":{"alias":"alias1","index":"index1","routing":"routing1","search_routing":"searchRouting1"}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1").Routing("routing1").SearchRouting("searchRouting1", "searchRouting2"),
- Expected: `{"add":{"alias":"alias1","index":"index1","routing":"routing1","search_routing":"searchRouting1,searchRouting2"}}`,
- },
- {
- Action: NewAliasAddAction("alias1").Index("index1").Filter(NewTermQuery("user", "olivere")),
- Expected: `{"add":{"alias":"alias1","filter":{"term":{"user":"olivere"}},"index":"index1"}}`,
- },
- }
-
- for i, tt := range tests {
- src, err := tt.Action.Source()
- if err != nil {
- if !tt.Invalid {
- t.Errorf("#%d: expected to succeed", i)
- }
- } else {
- if tt.Invalid {
- t.Errorf("#%d: expected to fail", i)
- } else {
- dst, err := json.Marshal(src)
- if err != nil {
- t.Fatal(err)
- }
- if want, have := tt.Expected, string(dst); want != have {
- t.Errorf("#%d: expected %s, got %s", i, want, have)
- }
- }
- }
- }
-}
-
-func TestAliasRemoveAction(t *testing.T) {
- var tests = []struct {
- Action *AliasRemoveAction
- Expected string
- Invalid bool
- }{
- {
- Action: NewAliasRemoveAction(""),
- Invalid: true,
- },
- {
- Action: NewAliasRemoveAction("alias1"),
- Invalid: true,
- },
- {
- Action: NewAliasRemoveAction("").Index("index1"),
- Invalid: true,
- },
- {
- Action: NewAliasRemoveAction("alias1").Index("index1"),
- Expected: `{"remove":{"alias":"alias1","index":"index1"}}`,
- },
- {
- Action: NewAliasRemoveAction("alias1").Index("index1", "index2"),
- Expected: `{"remove":{"alias":"alias1","indices":["index1","index2"]}}`,
- },
- }
-
- for i, tt := range tests {
- src, err := tt.Action.Source()
- if err != nil {
- if !tt.Invalid {
- t.Errorf("#%d: expected to succeed", i)
- }
- } else {
- if tt.Invalid {
- t.Errorf("#%d: expected to fail", i)
- } else {
- dst, err := json.Marshal(src)
- if err != nil {
- t.Fatal(err)
- }
- if want, have := tt.Expected, string(dst); want != have {
- t.Errorf("#%d: expected %s, got %s", i, want, have)
- }
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping.go
index 2f8a35e4c..03f26ca91 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping.go
@@ -10,13 +10,13 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesPutMappingService allows to register specific mapping definition
// for a specific type.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-put-mapping.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-put-mapping.html
// for details.
type IndicesPutMappingService struct {
client *Client
@@ -142,7 +142,7 @@ func (s *IndicesPutMappingService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
@@ -202,12 +202,7 @@ func (s *IndicesPutMappingService) Do(ctx context.Context) (*PutMappingResponse,
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -222,7 +217,5 @@ func (s *IndicesPutMappingService) Do(ctx context.Context) (*PutMappingResponse,
// PutMappingResponse is the response of IndicesPutMappingService.Do.
type PutMappingResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping_test.go
deleted file mode 100644
index 644e1187a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_mapping_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestPutMappingURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Type string
- Expected string
- }{
- {
- []string{},
- "doc",
- "/_mapping/doc",
- },
- {
- []string{"*"},
- "doc",
- "/%2A/_mapping/doc",
- },
- {
- []string{"store-1", "store-2"},
- "doc",
- "/store-1%2Cstore-2/_mapping/doc",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.PutMapping().Index(test.Indices...).Type(test.Type).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestMappingLifecycle(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- //client := setupTestClientAndCreateIndexAndLog(t)
-
- // Create index
- createIndex, err := client.CreateIndex(testIndexName3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex)
- }
-
- mapping := `{
- "doc":{
- "properties":{
- "field":{
- "type":"keyword"
- }
- }
- }
- }`
-
- putresp, err := client.PutMapping().Index(testIndexName3).Type("doc").BodyString(mapping).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected put mapping to succeed; got: %v", err)
- }
- if putresp == nil {
- t.Fatalf("expected put mapping response; got: %v", putresp)
- }
- if !putresp.Acknowledged {
- t.Fatalf("expected put mapping ack; got: %v", putresp.Acknowledged)
- }
-
- getresp, err := client.GetMapping().Index(testIndexName3).Type("doc").Do(context.TODO())
- if err != nil {
- t.Fatalf("expected get mapping to succeed; got: %v", err)
- }
- if getresp == nil {
- t.Fatalf("expected get mapping response; got: %v", getresp)
- }
- props, ok := getresp[testIndexName3]
- if !ok {
- t.Fatalf("expected JSON root to be of type map[string]interface{}; got: %#v", props)
- }
-
- // NOTE There is no Delete Mapping API in Elasticsearch 2.0
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings.go
index 1283eb669..20ae95207 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings.go
@@ -10,14 +10,14 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesPutSettingsService changes specific index level settings in
// real time.
//
// See the documentation at
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-update-settings.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-update-settings.html.
type IndicesPutSettingsService struct {
client *Client
pretty bool
@@ -118,7 +118,7 @@ func (s *IndicesPutSettingsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
@@ -165,12 +165,7 @@ func (s *IndicesPutSettingsService) Do(ctx context.Context) (*IndicesPutSettings
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -185,7 +180,5 @@ func (s *IndicesPutSettingsService) Do(ctx context.Context) (*IndicesPutSettings
// IndicesPutSettingsResponse is the response of IndicesPutSettingsService.Do.
type IndicesPutSettingsResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings_test.go
deleted file mode 100644
index 0ceea3ef8..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_settings_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesPutSettingsBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Expected string
- }{
- {
- []string{},
- "/_settings",
- },
- {
- []string{"*"},
- "/%2A/_settings",
- },
- {
- []string{"store-1", "store-2"},
- "/store-1%2Cstore-2/_settings",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IndexPutSettings().Index(test.Indices...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestIndicesSettingsLifecycle(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- body := `{
- "index":{
- "refresh_interval":"-1"
- }
- }`
-
- // Put settings
- putres, err := client.IndexPutSettings().Index(testIndexName).BodyString(body).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected put settings to succeed; got: %v", err)
- }
- if putres == nil {
- t.Fatalf("expected put settings response; got: %v", putres)
- }
- if !putres.Acknowledged {
- t.Fatalf("expected put settings ack; got: %v", putres.Acknowledged)
- }
-
- // Read settings
- getres, err := client.IndexGetSettings().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected get mapping to succeed; got: %v", err)
- }
- if getres == nil {
- t.Fatalf("expected get mapping response; got: %v", getres)
- }
-
- // Check settings
- index, found := getres[testIndexName]
- if !found {
- t.Fatalf("expected to return settings for index %q; got: %#v", testIndexName, getres)
- }
- // Retrieve "index" section of the settings for index testIndexName
- sectionIntf, ok := index.Settings["index"]
- if !ok {
- t.Fatalf("expected settings to have %q field; got: %#v", "index", getres)
- }
- section, ok := sectionIntf.(map[string]interface{})
- if !ok {
- t.Fatalf("expected settings to be of type map[string]interface{}; got: %#v", getres)
- }
- refintv, ok := section["refresh_interval"]
- if !ok {
- t.Fatalf(`expected JSON to include "refresh_interval" field; got: %#v`, getres)
- }
- if got, want := refintv, "-1"; got != want {
- t.Fatalf("expected refresh_interval = %v; got: %v", want, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_put_template.go b/vendor/gopkg.in/olivere/elastic.v5/indices_put_template.go
index c0b959647..49df95f54 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_put_template.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_put_template.go
@@ -9,11 +9,11 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesPutTemplateService creates or updates index mappings.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-templates.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-templates.html.
type IndicesPutTemplateService struct {
client *Client
pretty bool
@@ -118,7 +118,7 @@ func (s *IndicesPutTemplateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.order != nil {
params.Set("order", fmt.Sprintf("%v", s.order))
@@ -181,12 +181,7 @@ func (s *IndicesPutTemplateService) Do(ctx context.Context) (*IndicesPutTemplate
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -201,7 +196,5 @@ func (s *IndicesPutTemplateService) Do(ctx context.Context) (*IndicesPutTemplate
// IndicesPutTemplateResponse is the response of IndicesPutTemplateService.Do.
type IndicesPutTemplateResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged,omitempty"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_refresh.go b/vendor/gopkg.in/olivere/elastic.v5/indices_refresh.go
index f6c7f165e..dbc83ac2c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_refresh.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_refresh.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// RefreshService explicitly refreshes one or more indices.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-refresh.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/indices-refresh.html.
type RefreshService struct {
client *Client
index []string
@@ -73,11 +73,7 @@ func (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) {
}
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_refresh_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_refresh_test.go
deleted file mode 100644
index 8640fb602..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_refresh_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestRefreshBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Expected string
- }{
- {
- []string{},
- "/_refresh",
- },
- {
- []string{"index1"},
- "/index1/_refresh",
- },
- {
- []string{"index1", "index2"},
- "/index1%2Cindex2/_refresh",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.Refresh().Index(test.Indices...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestRefresh(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add some documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Refresh indices
- res, err := client.Refresh(testIndexName, testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected result; got nil")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_rollover.go b/vendor/gopkg.in/olivere/elastic.v5/indices_rollover.go
index 841b3836f..ef1cad033 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_rollover.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_rollover.go
@@ -10,14 +10,14 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesRolloverService rolls an alias over to a new index when the
// existing index is considered to be too large or too old.
//
// It is documented at
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-rollover-index.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-rollover-index.html.
type IndicesRolloverService struct {
client *Client
pretty bool
@@ -189,10 +189,10 @@ func (s *IndicesRolloverService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.dryRun {
- params.Set("dry_run", "true")
+ params.Set("dry_run", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -242,12 +242,7 @@ func (s *IndicesRolloverService) Do(ctx context.Context) (*IndicesRolloverRespon
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_rollover_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_rollover_test.go
deleted file mode 100644
index 81d7099e0..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_rollover_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestIndicesRolloverBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Alias string
- NewIndex string
- Expected string
- }{
- {
- "logs_write",
- "",
- "/logs_write/_rollover",
- },
- {
- "logs_write",
- "my_new_index_name",
- "/logs_write/_rollover/my_new_index_name",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.RolloverIndex(test.Alias).NewIndex(test.NewIndex).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestIndicesRolloverBodyConditions(t *testing.T) {
- client := setupTestClient(t)
- svc := NewIndicesRolloverService(client).
- Conditions(map[string]interface{}{
- "max_age": "7d",
- "max_docs": 1000,
- })
- data, err := json.Marshal(svc.getBody())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"conditions":{"max_age":"7d","max_docs":1000}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIndicesRolloverBodyAddCondition(t *testing.T) {
- client := setupTestClient(t)
- svc := NewIndicesRolloverService(client).
- AddCondition("max_age", "7d").
- AddCondition("max_docs", 1000)
- data, err := json.Marshal(svc.getBody())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"conditions":{"max_age":"7d","max_docs":1000}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIndicesRolloverBodyAddPredefinedConditions(t *testing.T) {
- client := setupTestClient(t)
- svc := NewIndicesRolloverService(client).
- AddMaxIndexAgeCondition("2d").
- AddMaxIndexDocsCondition(1000000)
- data, err := json.Marshal(svc.getBody())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"conditions":{"max_age":"2d","max_docs":1000000}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIndicesRolloverBodyComplex(t *testing.T) {
- client := setupTestClient(t)
- svc := NewIndicesRolloverService(client).
- AddMaxIndexAgeCondition("2d").
- AddMaxIndexDocsCondition(1000000).
- AddSetting("index.number_of_shards", 2).
- AddMapping("doc", map[string]interface{}{
- "properties": map[string]interface{}{
- "user": map[string]interface{}{
- "type": "keyword",
- },
- },
- })
- data, err := json.Marshal(svc.getBody())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"conditions":{"max_age":"2d","max_docs":1000000},"mappings":{"doc":{"properties":{"user":{"type":"keyword"}}}},"settings":{"index.number_of_shards":2}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_segments.go b/vendor/gopkg.in/olivere/elastic.v5/indices_segments.go
index 133d1101e..80ac3ed0c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_segments.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_segments.go
@@ -11,7 +11,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesSegmentsService provides low level segments information that a
@@ -20,7 +20,7 @@ import (
// optimization information, data "wasted" on deletes, and so on.
//
// Find further documentation at
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.1/indices-segments.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/indices-segments.html.
type IndicesSegmentsService struct {
client *Client
pretty bool
@@ -154,7 +154,7 @@ func (s *IndicesSegmentsService) Do(ctx context.Context) (*IndicesSegmentsRespon
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
+ res, err := s.client.PerformRequestWithOptions(ctx, PerformRequestOptions{
Method: "GET",
Path: path,
Params: params,
@@ -217,16 +217,7 @@ type IndexSegmentsDetails struct {
Version string `json:"version,omitempty"`
Compound bool `json:"compound,omitempty"`
MergeId string `json:"merge_id,omitempty"`
- Sort []*IndexSegmentsSort `json:"sort,omitempty"`
RAMTree []*IndexSegmentsRamTree `json:"ram_tree,omitempty"`
- Attributes map[string]string `json:"attributes,omitempty"`
-}
-
-type IndexSegmentsSort struct {
- Field string `json:"field,omitempty"`
- Mode string `json:"mode,omitempty"`
- Missing interface{} `json:"missing,omitempty"`
- Reverse bool `json:"reverse,omitempty"`
}
type IndexSegmentsRamTree struct {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_segments_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_segments_test.go
deleted file mode 100644
index 2ec181cc1..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_segments_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndicesSegments(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Expected string
- }{
- {
- []string{},
- "/_segments",
- },
- {
- []string{"index1"},
- "/index1/_segments",
- },
- {
- []string{"index1", "index2"},
- "/index1%2Cindex2/_segments",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.IndexSegments().Index(test.Indices...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestIndexSegments(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- segments, err := client.IndexSegments(testIndexName).Pretty(true).Human(true).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if segments == nil {
- t.Fatalf("expected response; got: %v", segments)
- }
- indices, found := segments.Indices[testIndexName]
- if !found {
- t.Fatalf("expected index information about index %v; got: %v", testIndexName, found)
- }
- shards, found := indices.Shards["0"]
- if !found {
- t.Fatalf("expected shard information about index %v", testIndexName)
- }
- if shards == nil {
- t.Fatalf("expected shard information to be != nil for index %v", testIndexName)
- }
- shard := shards[0]
- if shard == nil {
- t.Fatalf("expected shard information to be != nil for shard 0 in index %v", testIndexName)
- }
- if shard.Routing == nil {
- t.Fatalf("expected shard routing information to be != nil for index %v", testIndexName)
- }
- segmentDetail, found := shard.Segments["_0"]
- if !found {
- t.Fatalf("expected segment detail to be != nil for index %v", testIndexName)
- }
- if segmentDetail == nil {
- t.Fatalf("expected segment detail to be != nil for index %v", testIndexName)
- }
- if segmentDetail.NumDocs == 0 {
- t.Fatal("expected segment to contain >= 1 docs")
- }
- if len(segmentDetail.Attributes) == 0 {
- t.Fatalf("expected segment attributes map to contain at least one key, value pair for index %v", testIndexName)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_shrink.go b/vendor/gopkg.in/olivere/elastic.v5/indices_shrink.go
index 6ea72b281..ea20804a6 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_shrink.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_shrink.go
@@ -10,14 +10,14 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesShrinkService allows you to shrink an existing index into a
// new index with fewer primary shards.
//
// For further details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-shrink-index.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-shrink-index.html.
type IndicesShrinkService struct {
client *Client
pretty bool
@@ -102,7 +102,7 @@ func (s *IndicesShrinkService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -153,12 +153,7 @@ func (s *IndicesShrinkService) Do(ctx context.Context) (*IndicesShrinkResponse,
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -173,7 +168,6 @@ func (s *IndicesShrinkService) Do(ctx context.Context) (*IndicesShrinkResponse,
// IndicesShrinkResponse is the response of IndicesShrinkService.Do.
type IndicesShrinkResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
+ ShardsAcknowledged bool `json:"shards_acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_shrink_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_shrink_test.go
deleted file mode 100644
index 06ab7d923..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_shrink_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestIndicesShrinkBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Source string
- Target string
- Expected string
- }{
- {
- "my_source_index",
- "my_target_index",
- "/my_source_index/_shrink/my_target_index",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.ShrinkIndex(test.Source, test.Target).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_stats.go b/vendor/gopkg.in/olivere/elastic.v5/indices_stats.go
index 20d35a6d4..90ae6837a 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/indices_stats.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IndicesStatsService provides stats on various metrics of one or more
-// indices. See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/indices-stats.html.
+// indices. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-stats.html.
type IndicesStatsService struct {
client *Client
pretty bool
@@ -135,7 +135,7 @@ func (s *IndicesStatsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.groups) > 0 {
params.Set("groups", strings.Join(s.groups, ","))
@@ -180,11 +180,7 @@ func (s *IndicesStatsService) Do(ctx context.Context) (*IndicesStatsResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
@@ -243,20 +239,25 @@ type IndexStatsDocs struct {
}
type IndexStatsStore struct {
- Size string `json:"size,omitempty"` // human size, e.g. 119.3mb
- SizeInBytes int64 `json:"size_in_bytes,omitempty"`
+ Size string `json:"size,omitempty"` // human size, e.g. 119.3mb
+ SizeInBytes int64 `json:"size_in_bytes,omitempty"`
+ ThrottleTime string `json:"throttle_time,omitempty"` // human time, e.g. 0s
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis,omitempty"`
}
type IndexStatsIndexing struct {
- IndexTotal int64 `json:"index_total,omitempty"`
- IndexTime string `json:"index_time,omitempty"`
- IndexTimeInMillis int64 `json:"index_time_in_millis,omitempty"`
- IndexCurrent int64 `json:"index_current,omitempty"`
- DeleteTotal int64 `json:"delete_total,omitempty"`
- DeleteTime string `json:"delete_time,omitempty"`
- DeleteTimeInMillis int64 `json:"delete_time_in_millis,omitempty"`
- DeleteCurrent int64 `json:"delete_current,omitempty"`
- NoopUpdateTotal int64 `json:"noop_update_total,omitempty"`
+ IndexTotal int64 `json:"index_total,omitempty"`
+ IndexTime string `json:"index_time,omitempty"`
+ IndexTimeInMillis int64 `json:"index_time_in_millis,omitempty"`
+ IndexCurrent int64 `json:"index_current,omitempty"`
+ DeleteTotal int64 `json:"delete_total,omitempty"`
+ DeleteTime string `json:"delete_time,omitempty"`
+ DeleteTimeInMillis int64 `json:"delete_time_in_millis,omitempty"`
+ DeleteCurrent int64 `json:"delete_current,omitempty"`
+ NoopUpdateTotal int64 `json:"noop_update_total,omitempty"`
+ IsThrottled bool `json:"is_throttled,omitempty"`
+ ThrottleTime string `json:"throttle_time,omitempty"`
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis,omitempty"`
}
type IndexStatsGet struct {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/indices_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/indices_stats_test.go
deleted file mode 100644
index a3392c97a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/indices_stats_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIndexStatsBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Indices []string
- Metrics []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_stats",
- },
- {
- []string{"index1"},
- []string{},
- "/index1/_stats",
- },
- {
- []string{},
- []string{"metric1"},
- "/_stats/metric1",
- },
- {
- []string{"index1"},
- []string{"metric1"},
- "/index1/_stats/metric1",
- },
- {
- []string{"index1", "index2"},
- []string{"metric1"},
- "/index1%2Cindex2/_stats/metric1",
- },
- {
- []string{"index1", "index2"},
- []string{"metric1", "metric2"},
- "/index1%2Cindex2/_stats/metric1%2Cmetric2",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.IndexStats().Index(test.Indices...).Metric(test.Metrics...).buildURL()
- if err != nil {
- t.Fatalf("case #%d: %v", i+1, err)
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestIndexStats(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- stats, err := client.IndexStats(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if stats == nil {
- t.Fatalf("expected response; got: %v", stats)
- }
- stat, found := stats.Indices[testIndexName]
- if !found {
- t.Fatalf("expected stats about index %q; got: %v", testIndexName, found)
- }
- if stat.Total == nil {
- t.Fatalf("expected total to be != nil; got: %v", stat.Total)
- }
- if stat.Total.Docs == nil {
- t.Fatalf("expected total docs to be != nil; got: %v", stat.Total.Docs)
- }
- if stat.Total.Docs.Count == 0 {
- t.Fatalf("expected total docs count to be > 0; got: %d", stat.Total.Docs.Count)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline.go
index 78b6d04f2..1e33d9707 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline.go
@@ -10,11 +10,11 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IngestDeletePipelineService deletes pipelines by ID.
-// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/delete-pipeline-api.html.
+// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/delete-pipeline-api.html.
type IngestDeletePipelineService struct {
client *Client
pretty bool
@@ -67,7 +67,7 @@ func (s *IngestDeletePipelineService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -104,11 +104,7 @@ func (s *IngestDeletePipelineService) Do(ctx context.Context) (*IngestDeletePipe
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
if err != nil {
return nil, err
}
@@ -123,7 +119,5 @@ func (s *IngestDeletePipelineService) Do(ctx context.Context) (*IngestDeletePipe
// IngestDeletePipelineResponse is the response of IngestDeletePipelineService.Do.
type IngestDeletePipelineResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline_test.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline_test.go
deleted file mode 100644
index 1163e0f17..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_delete_pipeline_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestIngestDeletePipelineURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Id string
- Expected string
- }{
- {
- "my-pipeline-id",
- "/_ingest/pipeline/my-pipeline-id",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IngestDeletePipeline(test.Id).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline.go
index 16a683261..9a3357d7f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IngestGetPipelineService returns pipelines based on ID.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/get-pipeline-api.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/get-pipeline-api.html
// for documentation.
type IngestGetPipelineService struct {
client *Client
@@ -68,7 +68,7 @@ func (s *IngestGetPipelineService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -95,11 +95,7 @@ func (s *IngestGetPipelineService) Do(ctx context.Context) (IngestGetPipelineRes
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline_test.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline_test.go
deleted file mode 100644
index 009b717ca..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_get_pipeline_test.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestIngestGetPipelineURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Id []string
- Expected string
- }{
- {
- nil,
- "/_ingest/pipeline",
- },
- {
- []string{"my-pipeline-id"},
- "/_ingest/pipeline/my-pipeline-id",
- },
- {
- []string{"*"},
- "/_ingest/pipeline/%2A",
- },
- {
- []string{"pipeline-1", "pipeline-2"},
- "/_ingest/pipeline/pipeline-1%2Cpipeline-2",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IngestGetPipeline(test.Id...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestIngestLifecycle(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- // With the new ES Docker images, XPack is already installed and returns a pipeline. So we cannot test for "no pipelines". Skipping for now.
- /*
- // Get all pipelines (returns 404 that indicates an error)
- getres, err := client.IngestGetPipeline().Do(context.TODO())
- if err == nil {
- t.Fatal(err)
- }
- if getres != nil {
- t.Fatalf("expected no response, got %v", getres)
- }
- //*/
-
- // Add a pipeline
- pipelineDef := `{
- "description" : "reset retweets",
- "processors" : [
- {
- "set" : {
- "field": "retweets",
- "value": 0
- }
- }
- ]
-}`
- putres, err := client.IngestPutPipeline("my-pipeline").BodyString(pipelineDef).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if putres == nil {
- t.Fatal("expected response, got nil")
- }
- if want, have := true, putres.Acknowledged; want != have {
- t.Fatalf("expected ack = %v, got %v", want, have)
- }
-
- // Get all pipelines again
- getres, err := client.IngestGetPipeline().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if have := len(getres); have == 0 {
- t.Fatalf("expected at least 1 pipeline, got %d", have)
- }
- if _, found := getres["my-pipeline"]; !found {
- t.Fatalf("expected to find pipline with id %q", "my-pipeline")
- }
-
- // Get pipeline by ID
- getres, err = client.IngestGetPipeline("my-pipeline").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if want, have := 1, len(getres); want != have {
- t.Fatalf("expected %d pipelines, got %d", want, have)
- }
- if _, found := getres["my-pipeline"]; !found {
- t.Fatalf("expected to find pipline with id %q", "my-pipeline")
- }
-
- // Delete pipeline
- delres, err := client.IngestDeletePipeline("my-pipeline").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if delres == nil {
- t.Fatal("expected response, got nil")
- }
- if want, have := true, delres.Acknowledged; want != have {
- t.Fatalf("expected ack = %v, got %v", want, have)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline.go
index 5781e7072..315453e9d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline.go
@@ -10,13 +10,13 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IngestPutPipelineService adds pipelines and updates existing pipelines in
// the cluster.
//
-// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/put-pipeline-api.html.
+// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/put-pipeline-api.html.
type IngestPutPipelineService struct {
client *Client
pretty bool
@@ -84,7 +84,7 @@ func (s *IngestPutPipelineService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -132,12 +132,7 @@ func (s *IngestPutPipelineService) Do(ctx context.Context) (*IngestPutPipelineRe
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -152,7 +147,5 @@ func (s *IngestPutPipelineService) Do(ctx context.Context) (*IngestPutPipelineRe
// IngestPutPipelineResponse is the response of IngestPutPipelineService.Do.
type IngestPutPipelineResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline_test.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline_test.go
deleted file mode 100644
index 9609f2f53..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_put_pipeline_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestIngestPutPipelineURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Id string
- Expected string
- }{
- {
- "my-pipeline-id",
- "/_ingest/pipeline/my-pipeline-id",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IngestPutPipeline(test.Id).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline.go
index 213f97bbb..04015b459 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline.go
@@ -10,14 +10,14 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// IngestSimulatePipelineService executes a specific pipeline against the set of
// documents provided in the body of the request.
//
// The API is documented at
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/simulate-pipeline-api.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/simulate-pipeline-api.html.
type IngestSimulatePipelineService struct {
client *Client
pretty bool
@@ -85,7 +85,7 @@ func (s *IngestSimulatePipelineService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.verbose != nil {
params.Set("verbose", fmt.Sprintf("%v", *s.verbose))
@@ -127,12 +127,7 @@ func (s *IngestSimulatePipelineService) Do(ctx context.Context) (*IngestSimulate
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline_test.go b/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline_test.go
deleted file mode 100644
index a254f85ff..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/ingest_simulate_pipeline_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestIngestSimulatePipelineURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Id string
- Expected string
- }{
- {
- "",
- "/_ingest/pipeline/_simulate",
- },
- {
- "my-pipeline-id",
- "/_ingest/pipeline/my-pipeline-id/_simulate",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.IngestSimulatePipeline().Id(test.Id).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/inner_hit_test.go b/vendor/gopkg.in/olivere/elastic.v5/inner_hit_test.go
deleted file mode 100644
index fd9bd2e8a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/inner_hit_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestInnerHitEmpty(t *testing.T) {
- hit := NewInnerHit()
- src, err := hit.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestInnerHitWithName(t *testing.T) {
- hit := NewInnerHit().Name("comments")
- src, err := hit.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"name":"comments"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/mget.go b/vendor/gopkg.in/olivere/elastic.v5/mget.go
index 5202a9603..0f2894854 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/mget.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/mget.go
@@ -16,7 +16,7 @@ import (
// a docs array with all the fetched documents, each element similar
// in structure to a document provided by the Get API.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-multi-get.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-multi-get.html
// for details.
type MgetService struct {
client *Client
@@ -124,12 +124,7 @@ func (s *MgetService) Do(ctx context.Context) (*MgetResponse, error) {
}
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
if err != nil {
return nil, err
}
@@ -199,8 +194,8 @@ func (item *MultiGetItem) Version(version int64) *MultiGetItem {
return item
}
-// VersionType can be "internal", "external", "external_gt", or "external_gte".
-// See org.elasticsearch.index.VersionType in Elasticsearch source.
+// VersionType can be "internal", "external", "external_gt", "external_gte",
+// or "force". See org.elasticsearch.index.VersionType in Elasticsearch source.
// It is "internal" by default.
func (item *MultiGetItem) VersionType(versionType string) *MultiGetItem {
item.versionType = versionType
diff --git a/vendor/gopkg.in/olivere/elastic.v5/mget_test.go b/vendor/gopkg.in/olivere/elastic.v5/mget_test.go
deleted file mode 100644
index 6b3ecd9f6..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/mget_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestMultiGet(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add some documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Count documents
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Errorf("expected Count = %d; got %d", 3, count)
- }
-
- // Get documents 1 and 3
- res, err := client.MultiGet().
- Add(NewMultiGetItem().Index(testIndexName).Type("doc").Id("1")).
- Add(NewMultiGetItem().Index(testIndexName).Type("doc").Id("3")).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected result to be != nil; got nil")
- }
- if res.Docs == nil {
- t.Fatal("expected result docs to be != nil; got nil")
- }
- if len(res.Docs) != 2 {
- t.Fatalf("expected to have 2 docs; got %d", len(res.Docs))
- }
-
- item := res.Docs[0]
- if item.Error != nil {
- t.Errorf("expected no error on item 0; got %v", item.Error)
- }
- if item.Source == nil {
- t.Errorf("expected Source != nil; got %v", item.Source)
- }
- var doc tweet
- if err := json.Unmarshal(*item.Source, &doc); err != nil {
- t.Fatalf("expected to unmarshal item Source; got %v", err)
- }
- if doc.Message != tweet1.Message {
- t.Errorf("expected Message of first tweet to be %q; got %q", tweet1.Message, doc.Message)
- }
-
- item = res.Docs[1]
- if item.Error != nil {
- t.Errorf("expected no error on item 1; got %v", item.Error)
- }
- if item.Source == nil {
- t.Errorf("expected Source != nil; got %v", item.Source)
- }
- if err := json.Unmarshal(*item.Source, &doc); err != nil {
- t.Fatalf("expected to unmarshal item Source; got %v", err)
- }
- if doc.Message != tweet3.Message {
- t.Errorf("expected Message of second tweet to be %q; got %q", tweet3.Message, doc.Message)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/msearch.go b/vendor/gopkg.in/olivere/elastic.v5/msearch.go
index c1a589a97..bdedded4a 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/msearch.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/msearch.go
@@ -14,17 +14,17 @@ import (
// MultiSearch executes one or more searches in one roundtrip.
type MultiSearchService struct {
- client *Client
- requests []*SearchRequest
- indices []string
- pretty bool
+ client *Client
+ requests []*SearchRequest
+ indices []string
+ pretty bool
maxConcurrentRequests *int
preFilterShardSize *int
}
func NewMultiSearchService(client *Client) *MultiSearchService {
builder := &MultiSearchService{
- client: client,
+ client: client,
}
return builder
}
@@ -92,12 +92,7 @@ func (s *MultiSearchService) Do(ctx context.Context) (*MultiSearchResult, error)
body := strings.Join(lines, "\n") + "\n" // add trailing \n
// Get response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/msearch_test.go b/vendor/gopkg.in/olivere/elastic.v5/msearch_test.go
deleted file mode 100644
index d25e2cc28..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/msearch_test.go
+++ /dev/null
@@ -1,303 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- _ "net/http"
- "testing"
-)
-
-func TestMultiSearch(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- // client := setupTestClientAndCreateIndexAndLog(t)
-
- tweet1 := tweet{
- User: "olivere",
- Message: "Welcome to Golang and Elasticsearch.",
- Tags: []string{"golang", "elasticsearch"},
- }
- tweet2 := tweet{
- User: "olivere",
- Message: "Another unrelated topic.",
- Tags: []string{"golang"},
- }
- tweet3 := tweet{
- User: "sandrae",
- Message: "Cycling is fun.",
- Tags: []string{"sports", "cycling"},
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Spawn two search queries with one roundtrip
- q1 := NewMatchAllQuery()
- q2 := NewTermQuery("tags", "golang")
-
- sreq1 := NewSearchRequest().Index(testIndexName, testIndexName2).
- Source(NewSearchSource().Query(q1).Size(10))
- sreq2 := NewSearchRequest().Index(testIndexName).Type("doc").
- Source(NewSearchSource().Query(q2))
-
- searchResult, err := client.MultiSearch().
- Add(sreq1, sreq2).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Responses == nil {
- t.Fatal("expected responses != nil; got nil")
- }
- if len(searchResult.Responses) != 2 {
- t.Fatalf("expected 2 responses; got %d", len(searchResult.Responses))
- }
-
- sres := searchResult.Responses[0]
- if sres.Hits == nil {
- t.Errorf("expected Hits != nil; got nil")
- }
- if sres.Hits.TotalHits != 3 {
- t.Errorf("expected Hits.TotalHits = %d; got %d", 3, sres.Hits.TotalHits)
- }
- if len(sres.Hits.Hits) != 3 {
- t.Errorf("expected len(Hits.Hits) = %d; got %d", 3, len(sres.Hits.Hits))
- }
- for _, hit := range sres.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-
- sres = searchResult.Responses[1]
- if sres.Hits == nil {
- t.Errorf("expected Hits != nil; got nil")
- }
- if sres.Hits.TotalHits != 2 {
- t.Errorf("expected Hits.TotalHits = %d; got %d", 2, sres.Hits.TotalHits)
- }
- if len(sres.Hits.Hits) != 2 {
- t.Errorf("expected len(Hits.Hits) = %d; got %d", 2, len(sres.Hits.Hits))
- }
- for _, hit := range sres.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestMultiSearchWithStrings(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- // client := setupTestClientAndCreateIndexAndLog(t)
-
- tweet1 := tweet{
- User: "olivere",
- Message: "Welcome to Golang and Elasticsearch.",
- Tags: []string{"golang", "elasticsearch"},
- }
- tweet2 := tweet{
- User: "olivere",
- Message: "Another unrelated topic.",
- Tags: []string{"golang"},
- }
- tweet3 := tweet{
- User: "sandrae",
- Message: "Cycling is fun.",
- Tags: []string{"sports", "cycling"},
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Spawn two search queries with one roundtrip
- sreq1 := NewSearchRequest().Index(testIndexName, testIndexName2).
- Source(`{"query":{"match_all":{}}}`)
- sreq2 := NewSearchRequest().Index(testIndexName).Type("doc").
- Source(`{"query":{"term":{"tags":"golang"}}}`)
-
- searchResult, err := client.MultiSearch().
- Add(sreq1, sreq2).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Responses == nil {
- t.Fatal("expected responses != nil; got nil")
- }
- if len(searchResult.Responses) != 2 {
- t.Fatalf("expected 2 responses; got %d", len(searchResult.Responses))
- }
-
- sres := searchResult.Responses[0]
- if sres.Hits == nil {
- t.Errorf("expected Hits != nil; got nil")
- }
- if sres.Hits.TotalHits != 3 {
- t.Errorf("expected Hits.TotalHits = %d; got %d", 3, sres.Hits.TotalHits)
- }
- if len(sres.Hits.Hits) != 3 {
- t.Errorf("expected len(Hits.Hits) = %d; got %d", 3, len(sres.Hits.Hits))
- }
- for _, hit := range sres.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-
- sres = searchResult.Responses[1]
- if sres.Hits == nil {
- t.Errorf("expected Hits != nil; got nil")
- }
- if sres.Hits.TotalHits != 2 {
- t.Errorf("expected Hits.TotalHits = %d; got %d", 2, sres.Hits.TotalHits)
- }
- if len(sres.Hits.Hits) != 2 {
- t.Errorf("expected len(Hits.Hits) = %d; got %d", 2, len(sres.Hits.Hits))
- }
- for _, hit := range sres.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestMultiSearchWithOneRequest(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere",
- Message: "Welcome to Golang and Elasticsearch.",
- Tags: []string{"golang", "elasticsearch"},
- }
- tweet2 := tweet{
- User: "olivere",
- Message: "Another unrelated topic.",
- Tags: []string{"golang"},
- }
- tweet3 := tweet{
- User: "sandrae",
- Message: "Cycling is fun.",
- Tags: []string{"sports", "cycling"},
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Spawn two search queries with one roundtrip
- query := NewMatchAllQuery()
- source := NewSearchSource().Query(query).Size(10)
- sreq := NewSearchRequest().Source(source)
-
- searchResult, err := client.MultiSearch().
- Index(testIndexName).
- Add(sreq).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Responses == nil {
- t.Fatal("expected responses != nil; got nil")
- }
- if len(searchResult.Responses) != 1 {
- t.Fatalf("expected 1 responses; got %d", len(searchResult.Responses))
- }
-
- sres := searchResult.Responses[0]
- if sres.Hits == nil {
- t.Errorf("expected Hits != nil; got nil")
- }
- if sres.Hits.TotalHits != 3 {
- t.Errorf("expected Hits.TotalHits = %d; got %d", 3, sres.Hits.TotalHits)
- }
- if len(sres.Hits.Hits) != 3 {
- t.Errorf("expected len(Hits.Hits) = %d; got %d", 3, len(sres.Hits.Hits))
- }
- for _, hit := range sres.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/mtermvectors.go b/vendor/gopkg.in/olivere/elastic.v5/mtermvectors.go
index 755718e67..da0ca70c5 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/mtermvectors.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/mtermvectors.go
@@ -11,14 +11,14 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// MultiTermvectorService returns information and statistics on terms in the
// fields of a particular document. The document could be stored in the
// index or artificially provided by the user.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-multi-termvectors.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-multi-termvectors.html
// for documentation.
type MultiTermvectorService struct {
client *Client
@@ -198,7 +198,7 @@ func (s *MultiTermvectorService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.fieldStatistics != nil {
params.Set("field_statistics", fmt.Sprintf("%v", *s.fieldStatistics))
@@ -278,12 +278,7 @@ func (s *MultiTermvectorService) Do(ctx context.Context) (*MultiTermvectorRespon
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/mtermvectors_test.go b/vendor/gopkg.in/olivere/elastic.v5/mtermvectors_test.go
deleted file mode 100644
index 5f90cd5e2..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/mtermvectors_test.go
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestMultiTermVectorsValidateAndBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Index string
- Type string
- Expected string
- ExpectValidateFailure bool
- }{
- // #0: No index, no type
- {
- "",
- "",
- "/_mtermvectors",
- false,
- },
- // #1: Index only
- {
- "twitter",
- "",
- "/twitter/_mtermvectors",
- false,
- },
- // #2: Type without index
- {
- "",
- "doc",
- "",
- true,
- },
- // #3: Both index and type
- {
- "twitter",
- "doc",
- "/twitter/doc/_mtermvectors",
- false,
- },
- }
-
- for i, test := range tests {
- builder := client.MultiTermVectors().Index(test.Index).Type(test.Type)
- // Validate
- err := builder.Validate()
- if err != nil {
- if !test.ExpectValidateFailure {
- t.Errorf("#%d: expected no error, got: %v", i, err)
- continue
- }
- } else {
- if test.ExpectValidateFailure {
- t.Errorf("#%d: expected error, got: nil", i)
- continue
- }
- // Build
- path, _, err := builder.buildURL()
- if err != nil {
- t.Errorf("#%d: expected no error, got: %v", i, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("#%d: expected %q; got: %q", i, test.Expected, path)
- }
- }
- }
-}
-
-func TestMultiTermVectorsWithIds(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Count documents
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if count != 3 {
- t.Errorf("expected Count = %d; got %d", 3, count)
- }
-
- // MultiTermVectors by specifying ID by 1 and 3
- field := "Message"
- res, err := client.MultiTermVectors().
- Index(testIndexName).
- Type("doc").
- Add(NewMultiTermvectorItem().Index(testIndexName).Type("doc").Id("1").Fields(field)).
- Add(NewMultiTermvectorItem().Index(testIndexName).Type("doc").Id("3").Fields(field)).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected to return information and statistics")
- }
- if res.Docs == nil {
- t.Fatal("expected result docs to be != nil; got nil")
- }
- if len(res.Docs) != 2 {
- t.Fatalf("expected to have 2 docs; got %d", len(res.Docs))
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/nodes_info.go b/vendor/gopkg.in/olivere/elastic.v5/nodes_info.go
index 9f1422a69..b3687d689 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/nodes_info.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/nodes_info.go
@@ -11,12 +11,12 @@ import (
"strings"
"time"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// NodesInfoService allows to retrieve one or more or all of the
// cluster nodes information.
-// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/cluster-nodes-info.html.
+// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-nodes-info.html.
type NodesInfoService struct {
client *Client
pretty bool
@@ -89,7 +89,7 @@ func (s *NodesInfoService) buildURL() (string, url.Values, error) {
params.Set("human", fmt.Sprintf("%v", *s.human))
}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
return path, params, nil
}
@@ -113,11 +113,7 @@ func (s *NodesInfoService) Do(ctx context.Context) (*NodesInfoResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/nodes_info_test.go b/vendor/gopkg.in/olivere/elastic.v5/nodes_info_test.go
deleted file mode 100644
index 41d997584..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/nodes_info_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestNodesInfo(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
-
- info, err := client.NodesInfo().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if info == nil {
- t.Fatal("expected nodes info")
- }
-
- if info.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", info.ClusterName)
- }
- if len(info.Nodes) == 0 {
- t.Errorf("expected some nodes; got: %d", len(info.Nodes))
- }
- for id, node := range info.Nodes {
- if id == "" {
- t.Errorf("expected node id; got: %q", id)
- }
- if node == nil {
- t.Fatalf("expected node info; got: %v", node)
- }
- if node.IP == "" {
- t.Errorf("expected node IP; got: %q", node.IP)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/nodes_stats.go b/vendor/gopkg.in/olivere/elastic.v5/nodes_stats.go
index 7c5f0c9d6..a955bb426 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/nodes_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/nodes_stats.go
@@ -11,7 +11,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// NodesStatsService returns node statistics.
@@ -165,7 +165,7 @@ func (s *NodesStatsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.completionFields) > 0 {
params.Set("completion_fields", strings.Join(s.completionFields, ","))
@@ -213,11 +213,7 @@ func (s *NodesStatsService) Do(ctx context.Context) (*NodesStatsResponse, error)
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
@@ -320,21 +316,26 @@ type NodesStatsDocsStats struct {
}
type NodesStatsStoreStats struct {
- Size string `json:"size"`
- SizeInBytes int64 `json:"size_in_bytes"`
+ Size string `json:"size"`
+ SizeInBytes int64 `json:"size_in_bytes"`
+ ThrottleTime string `json:"throttle_time"`
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis"`
}
type NodesStatsIndexingStats struct {
- IndexTotal int64 `json:"index_total"`
- IndexTime string `json:"index_time"`
- IndexTimeInMillis int64 `json:"index_time_in_millis"`
- IndexCurrent int64 `json:"index_current"`
- IndexFailed int64 `json:"index_failed"`
- DeleteTotal int64 `json:"delete_total"`
- DeleteTime string `json:"delete_time"`
- DeleteTimeInMillis int64 `json:"delete_time_in_millis"`
- DeleteCurrent int64 `json:"delete_current"`
- NoopUpdateTotal int64 `json:"noop_update_total"`
+ IndexTotal int64 `json:"index_total"`
+ IndexTime string `json:"index_time"`
+ IndexTimeInMillis int64 `json:"index_time_in_millis"`
+ IndexCurrent int64 `json:"index_current"`
+ IndexFailed int64 `json:"index_failed"`
+ DeleteTotal int64 `json:"delete_total"`
+ DeleteTime string `json:"delete_time"`
+ DeleteTimeInMillis int64 `json:"delete_time_in_millis"`
+ DeleteCurrent int64 `json:"delete_current"`
+ NoopUpdateTotal int64 `json:"noop_update_total"`
+ IsThrottled bool `json:"is_throttled"`
+ ThrottleTime string `json:"throttle_time"`
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis"`
Types map[string]*NodesStatsIndexingStats `json:"types"` // stats for individual types
}
@@ -494,8 +495,10 @@ type NodesStatsRequestCacheStats struct {
}
type NodesStatsRecoveryStats struct {
- CurrentAsSource int `json:"current_as_source"`
- CurrentAsTarget int `json:"current_as_target"`
+ CurrentAsSource int `json:"current_as_source"`
+ CurrentAsTarget int `json:"current_as_target"`
+ ThrottleTime string `json:"throttle_time"`
+ ThrottleTimeInMillis int64 `json:"throttle_time_in_millis"`
}
type NodesStatsNodeOS struct {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/nodes_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/nodes_stats_test.go
deleted file mode 100644
index 4b249a2f4..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/nodes_stats_test.go
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestNodesStats(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
-
- info, err := client.NodesStats().Human(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if info == nil {
- t.Fatal("expected nodes stats")
- }
-
- if info.ClusterName == "" {
- t.Errorf("expected cluster name; got: %q", info.ClusterName)
- }
- if len(info.Nodes) == 0 {
- t.Errorf("expected some nodes; got: %d", len(info.Nodes))
- }
- for id, node := range info.Nodes {
- if id == "" {
- t.Errorf("expected node id; got: %q", id)
- }
- if node == nil {
- t.Fatalf("expected node info; got: %v", node)
- }
- if len(node.Name) == 0 {
- t.Errorf("expected node name; got: %q", node.Name)
- }
- if node.Timestamp == 0 {
- t.Errorf("expected timestamp; got: %q", node.Timestamp)
- }
- }
-}
-
-func TestNodesStatsBuildURL(t *testing.T) {
- tests := []struct {
- NodeIds []string
- Metrics []string
- IndexMetrics []string
- Expected string
- }{
- {
- NodeIds: nil,
- Metrics: nil,
- IndexMetrics: nil,
- Expected: "/_nodes/stats",
- },
- {
- NodeIds: []string{"node1"},
- Metrics: nil,
- IndexMetrics: nil,
- Expected: "/_nodes/node1/stats",
- },
- {
- NodeIds: []string{"node1", "node2"},
- Metrics: nil,
- IndexMetrics: nil,
- Expected: "/_nodes/node1%2Cnode2/stats",
- },
- {
- NodeIds: nil,
- Metrics: []string{"indices"},
- IndexMetrics: nil,
- Expected: "/_nodes/stats/indices",
- },
- {
- NodeIds: nil,
- Metrics: []string{"indices", "jvm"},
- IndexMetrics: nil,
- Expected: "/_nodes/stats/indices%2Cjvm",
- },
- {
- NodeIds: []string{"node1"},
- Metrics: []string{"indices", "jvm"},
- IndexMetrics: nil,
- Expected: "/_nodes/node1/stats/indices%2Cjvm",
- },
- {
- NodeIds: nil,
- Metrics: nil,
- IndexMetrics: []string{"fielddata"},
- Expected: "/_nodes/stats/_all/fielddata",
- },
- {
- NodeIds: []string{"node1"},
- Metrics: nil,
- IndexMetrics: []string{"fielddata"},
- Expected: "/_nodes/node1/stats/_all/fielddata",
- },
- {
- NodeIds: nil,
- Metrics: []string{"indices"},
- IndexMetrics: []string{"fielddata"},
- Expected: "/_nodes/stats/indices/fielddata",
- },
- {
- NodeIds: []string{"node1"},
- Metrics: []string{"indices"},
- IndexMetrics: []string{"fielddata"},
- Expected: "/_nodes/node1/stats/indices/fielddata",
- },
- {
- NodeIds: []string{"node1", "node2"},
- Metrics: []string{"indices", "jvm"},
- IndexMetrics: []string{"fielddata", "docs"},
- Expected: "/_nodes/node1%2Cnode2/stats/indices%2Cjvm/fielddata%2Cdocs",
- },
- }
-
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- for i, tt := range tests {
- svc := client.NodesStats().NodeId(tt.NodeIds...).Metric(tt.Metrics...).IndexMetric(tt.IndexMetrics...)
- path, _, err := svc.buildURL()
- if err != nil {
- t.Errorf("#%d: expected no error, got %v", i, err)
- } else {
- if want, have := tt.Expected, path; want != have {
- t.Errorf("#%d: expected %q, got %q", i, want, have)
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/percolate_test.go b/vendor/gopkg.in/olivere/elastic.v5/percolate_test.go
deleted file mode 100644
index 3b3b2efb7..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/percolate_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestPercolate(t *testing.T) {
- //client := setupTestClientAndCreateIndex(t, SetErrorLog(log.New(os.Stdout, "", 0)))
- //client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- // Create query index
- createQueryIndex, err := client.CreateIndex(testQueryIndex).Body(testQueryMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createQueryIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createQueryIndex)
- }
-
- // Add a document
- _, err = client.Index().
- Index(testQueryIndex).
- Type("doc").
- Id("1").
- BodyJson(`{"query":{"match":{"message":"bonsai tree"}}}`).
- Refresh("wait_for").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Percolate should return our registered query
- pq := NewPercolatorQuery().
- Field("query").
- DocumentType("doc").
- Document(doctype{Message: "A new bonsai tree in the office"})
- res, err := client.Search(testQueryIndex).Type("doc").Query(pq).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected results != nil; got nil")
- }
- if res.Hits == nil {
- t.Fatal("expected SearchResult.Hits != nil; got nil")
- }
- if got, want := res.Hits.TotalHits, int64(1); got != want {
- t.Fatalf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
- }
- if got, want := len(res.Hits.Hits), 1; got != want {
- t.Fatalf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
- }
- hit := res.Hits.Hits[0]
- if hit.Index != testQueryIndex {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testQueryIndex, hit.Index)
- }
- got := string(*hit.Source)
- expected := `{"query":{"match":{"message":"bonsai tree"}}}`
- if got != expected {
- t.Fatalf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ping.go b/vendor/gopkg.in/olivere/elastic.v5/ping.go
index 5c2d34f00..a97ddeceb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/ping.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/ping.go
@@ -86,7 +86,7 @@ func (s *PingService) Do(ctx context.Context) (*PingResult, int, error) {
params.Set("timeout", s.timeout)
}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(params) > 0 {
url_ += "?" + params.Encode()
diff --git a/vendor/gopkg.in/olivere/elastic.v5/ping_test.go b/vendor/gopkg.in/olivere/elastic.v5/ping_test.go
deleted file mode 100644
index 273913803..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/ping_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "net/http"
- "testing"
-)
-
-func TestPingGet(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- res, code, err := client.Ping(DefaultURL).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if code != http.StatusOK {
- t.Errorf("expected status code = %d; got %d", http.StatusOK, code)
- }
- if res == nil {
- t.Fatalf("expected to return result, got: %v", res)
- }
- if res.Name == "" {
- t.Errorf("expected Name != \"\"; got %q", res.Name)
- }
- if res.Version.Number == "" {
- t.Errorf("expected Version.Number != \"\"; got %q", res.Version.Number)
- }
-}
-
-func TestPingHead(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- res, code, err := client.Ping(DefaultURL).HttpHeadOnly(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if code != http.StatusOK {
- t.Errorf("expected status code = %d; got %d", http.StatusOK, code)
- }
- if res != nil {
- t.Errorf("expected not to return result, got: %v", res)
- }
-}
-
-func TestPingHeadFailure(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- res, code, err := client.
- Ping("http://127.0.0.1:9299").
- HttpHeadOnly(true).
- Do(context.TODO())
- if err == nil {
- t.Error("expected error, got nil")
- }
- if code == http.StatusOK {
- t.Errorf("expected status code != %d; got %d", http.StatusOK, code)
- }
- if res != nil {
- t.Errorf("expected not to return result, got: %v", res)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/plugins_test.go b/vendor/gopkg.in/olivere/elastic.v5/plugins_test.go
deleted file mode 100644
index 969f0b0e5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/plugins_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestClientPlugins(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Plugins()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestClientHasPlugin(t *testing.T) {
- client, err := NewClient()
- if err != nil {
- t.Fatal(err)
- }
- found, err := client.HasPlugin("no-such-plugin")
- if err != nil {
- t.Fatal(err)
- }
- if found {
- t.Fatalf("expected to not find plugin %q", "no-such-plugin")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/put_template.go b/vendor/gopkg.in/olivere/elastic.v5/put_template.go
new file mode 100644
index 000000000..5bd8423b5
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/put_template.go
@@ -0,0 +1,145 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// PutTemplateService creates or updates a search template.
+// The documentation can be found at
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-template.html.
+type PutTemplateService struct {
+ client *Client
+ pretty bool
+ id string
+ opType string
+ version *int
+ versionType string
+ bodyJson interface{}
+ bodyString string
+}
+
+// NewPutTemplateService creates a new PutTemplateService.
+func NewPutTemplateService(client *Client) *PutTemplateService {
+ return &PutTemplateService{
+ client: client,
+ }
+}
+
+// Id is the template ID.
+func (s *PutTemplateService) Id(id string) *PutTemplateService {
+ s.id = id
+ return s
+}
+
+// OpType is an explicit operation type.
+func (s *PutTemplateService) OpType(opType string) *PutTemplateService {
+ s.opType = opType
+ return s
+}
+
+// Version is an explicit version number for concurrency control.
+func (s *PutTemplateService) Version(version int) *PutTemplateService {
+ s.version = &version
+ return s
+}
+
+// VersionType is a specific version type.
+func (s *PutTemplateService) VersionType(versionType string) *PutTemplateService {
+ s.versionType = versionType
+ return s
+}
+
+// BodyJson is the document as a JSON serializable object.
+func (s *PutTemplateService) BodyJson(body interface{}) *PutTemplateService {
+ s.bodyJson = body
+ return s
+}
+
+// BodyString is the document as a string.
+func (s *PutTemplateService) BodyString(body string) *PutTemplateService {
+ s.bodyString = body
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *PutTemplateService) buildURL() (string, url.Values, error) {
+ // Build URL
+ path, err := uritemplates.Expand("/_search/template/{id}", map[string]string{
+ "id": s.id,
+ })
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.version != nil {
+ params.Set("version", fmt.Sprintf("%d", *s.version))
+ }
+ if s.versionType != "" {
+ params.Set("version_type", s.versionType)
+ }
+ if s.opType != "" {
+ params.Set("op_type", s.opType)
+ }
+
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *PutTemplateService) Validate() error {
+ var invalid []string
+ if s.id == "" {
+ invalid = append(invalid, "Id")
+ }
+ if s.bodyString == "" && s.bodyJson == nil {
+ invalid = append(invalid, "BodyJson")
+ }
+ if len(invalid) > 0 {
+ return fmt.Errorf("missing required fields: %v", invalid)
+ }
+ return nil
+}
+
+// Do executes the operation.
+func (s *PutTemplateService) Do(ctx context.Context) (*AcknowledgedResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Setup HTTP request body
+ var body interface{}
+ if s.bodyJson != nil {
+ body = s.bodyJson
+ } else {
+ body = s.bodyString
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return operation response
+ ret := new(AcknowledgedResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_insert/bulk_insert.go b/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_insert/bulk_insert.go
deleted file mode 100644
index 5a8ab39d0..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_insert/bulk_insert.go
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-// BulkInsert illustrates how to bulk insert documents into Elasticsearch.
-//
-// It uses two goroutines to do so. The first creates a simple document
-// and sends it to the second via a channel. The second goroutine collects
-// those documents, creates a bulk request that is added to a Bulk service
-// and committed to Elasticsearch after reaching a number of documents.
-// The number of documents after which a commit happens can be specified
-// via the "bulk-size" flag.
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-bulk.html
-// for details on the Bulk API in Elasticsearch.
-//
-// Example
-//
-// Bulk index 100.000 documents into the index "warehouse", type "product",
-// committing every set of 1.000 documents.
-//
-// bulk_insert -index=warehouse -type=product -n=100000 -bulk-size=1000
-//
-package main
-
-import (
- "context"
- "encoding/base64"
- "errors"
- "flag"
- "fmt"
- "log"
- "math/rand"
- "sync/atomic"
- "time"
-
- "golang.org/x/sync/errgroup"
- "github.com/olivere/elastic"
-)
-
-func main() {
- var (
- url = flag.String("url", "http://localhost:9200", "Elasticsearch URL")
- index = flag.String("index", "", "Elasticsearch index name")
- typ = flag.String("type", "", "Elasticsearch type name")
- sniff = flag.Bool("sniff", true, "Enable or disable sniffing")
- n = flag.Int("n", 0, "Number of documents to bulk insert")
- bulkSize = flag.Int("bulk-size", 0, "Number of documents to collect before committing")
- )
- flag.Parse()
- log.SetFlags(0)
- rand.Seed(time.Now().UnixNano())
-
- if *url == "" {
- log.Fatal("missing url parameter")
- }
- if *index == "" {
- log.Fatal("missing index parameter")
- }
- if *typ == "" {
- log.Fatal("missing type parameter")
- }
- if *n <= 0 {
- log.Fatal("n must be a positive number")
- }
- if *bulkSize <= 0 {
- log.Fatal("bulk-size must be a positive number")
- }
-
- // Create an Elasticsearch client
- client, err := elastic.NewClient(elastic.SetURL(*url), elastic.SetSniff(*sniff))
- if err != nil {
- log.Fatal(err)
- }
-
- // Setup a group of goroutines from the excellent errgroup package
- g, ctx := errgroup.WithContext(context.TODO())
-
- // The first goroutine will emit documents and send it to the second goroutine
- // via the docsc channel.
- // The second Goroutine will simply bulk insert the documents.
- type doc struct {
- ID string `json:"id"`
- Timestamp time.Time `json:"@timestamp"`
- }
- docsc := make(chan doc)
-
- begin := time.Now()
-
- // Goroutine to create documents
- g.Go(func() error {
- defer close(docsc)
-
- buf := make([]byte, 32)
- for i := 0; i < *n; i++ {
- // Generate a random ID
- _, err := rand.Read(buf)
- if err != nil {
- return err
- }
- id := base64.URLEncoding.EncodeToString(buf)
-
- // Construct the document
- d := doc{
- ID: id,
- Timestamp: time.Now(),
- }
-
- // Send over to 2nd goroutine, or cancel
- select {
- case docsc <- d:
- case <-ctx.Done():
- return ctx.Err()
- }
- }
- return nil
- })
-
- // Second goroutine will consume the documents sent from the first and bulk insert into ES
- var total uint64
- g.Go(func() error {
- bulk := client.Bulk().Index(*index).Type(*typ)
- for d := range docsc {
- // Simple progress
- current := atomic.AddUint64(&total, 1)
- dur := time.Since(begin).Seconds()
- sec := int(dur)
- pps := int64(float64(current) / dur)
- fmt.Printf("%10d | %6d req/s | %02d:%02d\r", current, pps, sec/60, sec%60)
-
- // Enqueue the document
- bulk.Add(elastic.NewBulkIndexRequest().Id(d.ID).Doc(d))
- if bulk.NumberOfActions() >= *bulkSize {
- // Commit
- res, err := bulk.Do(ctx)
- if err != nil {
- return err
- }
- if res.Errors {
- // Look up the failed documents with res.Failed(), and e.g. recommit
- return errors.New("bulk commit failed")
- }
- // "bulk" is reset after Do, so you can reuse it
- }
-
- select {
- default:
- case <-ctx.Done():
- return ctx.Err()
- }
- }
-
- // Commit the final batch before exiting
- if bulk.NumberOfActions() > 0 {
- _, err = bulk.Do(ctx)
- if err != nil {
- return err
- }
- }
- return nil
- })
-
- // Wait until all goroutines are finished
- if err := g.Wait(); err != nil {
- log.Fatal(err)
- }
-
- // Final results
- dur := time.Since(begin).Seconds()
- sec := int(dur)
- pps := int64(float64(total) / dur)
- fmt.Printf("%10d | %6d req/s | %02d:%02d\n", total, pps, sec/60, sec%60)
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_processor/main.go b/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_processor/main.go
deleted file mode 100644
index f13243297..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/recipes/bulk_processor/main.go
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-// BulkProcessor runs a bulk processing job that fills an index
-// given certain criteria like flush interval etc.
-//
-// Example
-//
-// bulk_processor -url=http://127.0.0.1:9200/bulk-processor-test?sniff=false -n=100000 -flush-interval=1s
-//
-package main
-
-import (
- "context"
- "flag"
- "fmt"
- "log"
- "math/rand"
- "os"
- "os/signal"
- "sync/atomic"
- "syscall"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/olivere/elastic"
- "github.com/olivere/elastic/config"
-)
-
-func main() {
- var (
- url = flag.String("url", "http://localhost:9200/bulk-processor-test", "Elasticsearch URL")
- numWorkers = flag.Int("num-workers", 4, "Number of workers")
- n = flag.Int64("n", -1, "Number of documents to process (-1 for unlimited)")
- flushInterval = flag.Duration("flush-interval", 1*time.Second, "Flush interval")
- bulkActions = flag.Int("bulk-actions", 0, "Number of bulk actions before committing")
- bulkSize = flag.Int("bulk-size", 0, "Size of bulk requests before committing")
- )
- flag.Parse()
- log.SetFlags(0)
-
- rand.Seed(time.Now().UnixNano())
-
- // Parse configuration from URL
- cfg, err := config.Parse(*url)
- if err != nil {
- log.Fatal(err)
- }
-
- // Create an Elasticsearch client from the parsed config
- client, err := elastic.NewClientFromConfig(cfg)
- if err != nil {
- log.Fatal(err)
- }
-
- // Drop old index
- exists, err := client.IndexExists(cfg.Index).Do(context.Background())
- if err != nil {
- log.Fatal(err)
- }
- if exists {
- _, err = client.DeleteIndex(cfg.Index).Do(context.Background())
- if err != nil {
- log.Fatal(err)
- }
- }
-
- // Create processor
- bulkp := elastic.NewBulkProcessorService(client).
- Name("bulk-test-processor").
- Stats(true).
- Backoff(elastic.StopBackoff{}).
- FlushInterval(*flushInterval).
- Workers(*numWorkers)
- if *bulkActions > 0 {
- bulkp = bulkp.BulkActions(*bulkActions)
- }
- if *bulkSize > 0 {
- bulkp = bulkp.BulkSize(*bulkSize)
- }
- p, err := bulkp.Do(context.Background())
- if err != nil {
- log.Fatal(err)
- }
-
- var created int64
- errc := make(chan error, 1)
- go func() {
- c := make(chan os.Signal, 1)
- signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
- <-c
- errc <- nil
- }()
-
- go func() {
- defer func() {
- if err := p.Close(); err != nil {
- errc <- err
- }
- }()
-
- type Doc struct {
- Timestamp time.Time `json:"@timestamp"`
- }
-
- for {
- current := atomic.AddInt64(&created, 1)
- if *n > 0 && current >= *n {
- errc <- nil
- return
- }
- r := elastic.NewBulkIndexRequest().
- Index(cfg.Index).
- Type("doc").
- Id(uuid.New().String()).
- Doc(Doc{Timestamp: time.Now()})
- p.Add(r)
-
- time.Sleep(time.Duration(rand.Intn(1000)) * time.Microsecond)
- }
- }()
-
- go func() {
- t := time.NewTicker(1 * time.Second)
- defer t.Stop()
- for range t.C {
- stats := p.Stats()
- written := atomic.LoadInt64(&created)
- var queued int64
- for _, w := range stats.Workers {
- queued += w.Queued
- }
- fmt.Printf("Queued=%5d Written=%8d Succeeded=%8d Failed=%8d Comitted=%6d Flushed=%6d\n",
- queued,
- written,
- stats.Succeeded,
- stats.Failed,
- stats.Committed,
- stats.Flushed,
- )
- }
- }()
-
- if err := <-errc; err != nil {
- log.Fatal(err)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/recipes/connect/connect.go b/vendor/gopkg.in/olivere/elastic.v5/recipes/connect/connect.go
deleted file mode 100644
index baff6c114..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/recipes/connect/connect.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-// Connect simply connects to Elasticsearch.
-//
-// Example
-//
-//
-// connect -url=http://127.0.0.1:9200 -sniff=false
-//
-package main
-
-import (
- "flag"
- "fmt"
- "log"
-
- "github.com/olivere/elastic"
-)
-
-func main() {
- var (
- url = flag.String("url", "http://localhost:9200", "Elasticsearch URL")
- sniff = flag.Bool("sniff", true, "Enable or disable sniffing")
- )
- flag.Parse()
- log.SetFlags(0)
-
- if *url == "" {
- *url = "http://127.0.0.1:9200"
- }
-
- // Create an Elasticsearch client
- client, err := elastic.NewClient(elastic.SetURL(*url), elastic.SetSniff(*sniff))
- if err != nil {
- log.Fatal(err)
- }
- _ = client
-
- // Just a status message
- fmt.Println("Connection succeeded")
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/recipes/sliced_scroll/sliced_scroll.go b/vendor/gopkg.in/olivere/elastic.v5/recipes/sliced_scroll/sliced_scroll.go
deleted file mode 100644
index d753a61cb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/recipes/sliced_scroll/sliced_scroll.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-// SlicedScroll illustrates scrolling through a set of documents
-// in parallel. It uses the sliced scrolling feature introduced
-// in Elasticsearch 5.0 to create a number of Goroutines, each
-// scrolling through a slice of the total results. A second goroutine
-// receives the hits from the set of goroutines scrolling through
-// the slices and simply counts the total number and the number of
-// documents received per slice.
-//
-// The speedup of sliced scrolling can be significant but is very
-// dependent on the specific use case.
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html#sliced-scroll
-// for details on sliced scrolling in Elasticsearch.
-//
-// Example
-//
-// Scroll with 4 parallel slices through an index called "products".
-// Use "_uid" as the default field:
-//
-// sliced_scroll -index=products -n=4
-//
-package main
-
-import (
- "context"
- "flag"
- "fmt"
- "io"
- "log"
- "sync"
- "sync/atomic"
- "time"
-
- "golang.org/x/sync/errgroup"
- "github.com/olivere/elastic"
-)
-
-func main() {
- var (
- url = flag.String("url", "http://localhost:9200", "Elasticsearch URL")
- index = flag.String("index", "", "Elasticsearch index name")
- typ = flag.String("type", "", "Elasticsearch type name")
- field = flag.String("field", "", "Slice field (must be numeric)")
- numSlices = flag.Int("n", 2, "Number of slices to use in parallel")
- sniff = flag.Bool("sniff", true, "Enable or disable sniffing")
- )
- flag.Parse()
- log.SetFlags(0)
-
- if *url == "" {
- log.Fatal("missing url parameter")
- }
- if *index == "" {
- log.Fatal("missing index parameter")
- }
- if *numSlices <= 0 {
- log.Fatal("n must be greater than zero")
- }
-
- // Create an Elasticsearch client
- client, err := elastic.NewClient(elastic.SetURL(*url), elastic.SetSniff(*sniff))
- if err != nil {
- log.Fatal(err)
- }
-
- // Setup a group of goroutines from the excellent errgroup package
- g, ctx := errgroup.WithContext(context.TODO())
-
- // Hits channel will be sent to from the first set of goroutines and consumed by the second
- type hit struct {
- Slice int
- Hit elastic.SearchHit
- }
- hitsc := make(chan hit)
-
- begin := time.Now()
-
- // Start a number of goroutines to parallelize scrolling
- var wg sync.WaitGroup
- for i := 0; i < *numSlices; i++ {
- wg.Add(1)
-
- slice := i
-
- // Prepare the query
- var query elastic.Query
- if *typ == "" {
- query = elastic.NewMatchAllQuery()
- } else {
- query = elastic.NewTypeQuery(*typ)
- }
-
- // Prepare the slice
- sliceQuery := elastic.NewSliceQuery().Id(i).Max(*numSlices)
- if *field != "" {
- sliceQuery = sliceQuery.Field(*field)
- }
-
- // Start goroutine for this sliced scroll
- g.Go(func() error {
- defer wg.Done()
- svc := client.Scroll(*index).Query(query).Slice(sliceQuery)
- for {
- res, err := svc.Do(ctx)
- if err == io.EOF {
- break
- }
- if err != nil {
- return err
- }
- for _, searchHit := range res.Hits.Hits {
- // Pass the hit to the hits channel, which will be consumed below
- select {
- case hitsc <- hit{Slice: slice, Hit: *searchHit}:
- case <-ctx.Done():
- return ctx.Err()
- }
- }
- }
- return nil
- })
- }
- go func() {
- // Wait until all scrolling is done
- wg.Wait()
- close(hitsc)
- }()
-
- // Second goroutine will consume the hits sent from the workers in first set of goroutines
- var total uint64
- totals := make([]uint64, *numSlices)
- g.Go(func() error {
- for hit := range hitsc {
- // We simply count the hits here.
- atomic.AddUint64(&totals[hit.Slice], 1)
- current := atomic.AddUint64(&total, 1)
- sec := int(time.Since(begin).Seconds())
- fmt.Printf("%8d | %02d:%02d\r", current, sec/60, sec%60)
- select {
- default:
- case <-ctx.Done():
- return ctx.Err()
- }
- }
- return nil
- })
-
- // Wait until all goroutines are finished
- if err := g.Wait(); err != nil {
- log.Fatal(err)
- }
-
- fmt.Printf("Scrolled through a total of %d documents in %v\n", total, time.Since(begin))
- for i := 0; i < *numSlices; i++ {
- fmt.Printf("Slice %2d received %d documents\n", i, totals[i])
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/reindex.go b/vendor/gopkg.in/olivere/elastic.v5/reindex.go
index 9cdd50a68..71e0807ee 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/reindex.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/reindex.go
@@ -11,7 +11,7 @@ import (
)
// ReindexService is a method to copy documents from one index to another.
-// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-reindex.html.
+// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.0/docs-reindex.html.
type ReindexService struct {
client *Client
pretty bool
@@ -175,7 +175,7 @@ func (s *ReindexService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.refresh != "" {
params.Set("refresh", s.refresh)
@@ -277,12 +277,7 @@ func (s *ReindexService) Do(ctx context.Context) (*BulkIndexByScrollResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -324,12 +319,7 @@ func (s *ReindexService) DoAsync(ctx context.Context) (*StartTaskResult, error)
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -346,7 +336,7 @@ func (s *ReindexService) DoAsync(ctx context.Context) (*StartTaskResult, error)
// ReindexSource specifies the source of a Reindex process.
type ReindexSource struct {
- searchType string // default in ES is "query_then_fetch"
+ searchType string
indices []string
types []string
routing *string
@@ -588,7 +578,7 @@ func (ri *ReindexRemoteInfo) Source() (interface{}, error) {
// ReindexDestination is the destination of a Reindex API call.
// It is basically the meta data of a BulkIndexRequest.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-reindex.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-reindex.html
// fsourcer details.
type ReindexDestination struct {
index string
@@ -647,7 +637,7 @@ func (r *ReindexDestination) Parent(parent string) *ReindexDestination {
// OpType specifies if this request should follow create-only or upsert
// behavior. This follows the OpType of the standard document index API.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-index_.html#operation-type
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#operation-type
// for details.
func (r *ReindexDestination) OpType(opType string) *ReindexDestination {
r.opType = opType
diff --git a/vendor/gopkg.in/olivere/elastic.v5/reindex_test.go b/vendor/gopkg.in/olivere/elastic.v5/reindex_test.go
deleted file mode 100644
index fadf4bfc7..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/reindex_test.go
+++ /dev/null
@@ -1,401 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestReindexSourceWithBodyMap(t *testing.T) {
- client := setupTestClient(t)
- out, err := client.Reindex().Body(map[string]interface{}{
- "source": map[string]interface{}{
- "index": "twitter",
- },
- "dest": map[string]interface{}{
- "index": "new_twitter",
- },
- }).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithBodyString(t *testing.T) {
- client := setupTestClient(t)
- got, err := client.Reindex().Body(`{"source":{"index":"twitter"},"dest":{"index":"new_twitter"}}`).getBody()
- if err != nil {
- t.Fatal(err)
- }
- want := `{"source":{"index":"twitter"},"dest":{"index":"new_twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithSourceIndexAndDestinationIndex(t *testing.T) {
- client := setupTestClient(t)
- out, err := client.Reindex().SourceIndex("twitter").DestinationIndex("new_twitter").getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithSourceAndDestinationAndVersionType(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter")
- dst := NewReindexDestination().Index("new_twitter").VersionType("external")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter","version_type":"external"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithSourceAndRemoteAndDestination(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter").RemoteInfo(
- NewReindexRemoteInfo().Host("http://otherhost:9200").
- Username("alice").
- Password("secret").
- ConnectTimeout("10s").
- SocketTimeout("1m"),
- )
- dst := NewReindexDestination().Index("new_twitter")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter"},"source":{"index":"twitter","remote":{"connect_timeout":"10s","host":"http://otherhost:9200","password":"secret","socket_timeout":"1m","username":"alice"}}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithSourceAndDestinationAndOpType(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter")
- dst := NewReindexDestination().Index("new_twitter").OpType("create")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter","op_type":"create"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithConflictsProceed(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter")
- dst := NewReindexDestination().Index("new_twitter").OpType("create")
- out, err := client.Reindex().Conflicts("proceed").Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"conflicts":"proceed","dest":{"index":"new_twitter","op_type":"create"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithProceedOnVersionConflict(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter")
- dst := NewReindexDestination().Index("new_twitter").OpType("create")
- out, err := client.Reindex().ProceedOnVersionConflict().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"conflicts":"proceed","dest":{"index":"new_twitter","op_type":"create"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithQuery(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter").Type("doc").Query(NewTermQuery("user", "olivere"))
- dst := NewReindexDestination().Index("new_twitter")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter"},"source":{"index":"twitter","query":{"term":{"user":"olivere"}},"type":"doc"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithMultipleSourceIndicesAndTypes(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter", "blog").Type("doc", "post")
- dst := NewReindexDestination().Index("all_together")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"all_together"},"source":{"index":["twitter","blog"],"type":["doc","post"]}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithSourceAndSize(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter").Sort("date", false)
- dst := NewReindexDestination().Index("new_twitter")
- out, err := client.Reindex().Size(10000).Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter"},"size":10000,"source":{"index":"twitter","sort":[{"date":{"order":"desc"}}]}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithScript(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("twitter")
- dst := NewReindexDestination().Index("new_twitter").VersionType("external")
- scr := NewScriptInline("if (ctx._source.foo == 'bar') {ctx._version++; ctx._source.remove('foo')}")
- out, err := client.Reindex().Source(src).Destination(dst).Script(scr).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"new_twitter","version_type":"external"},"script":{"source":"if (ctx._source.foo == 'bar') {ctx._version++; ctx._source.remove('foo')}"},"source":{"index":"twitter"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindexSourceWithRouting(t *testing.T) {
- client := setupTestClient(t)
- src := NewReindexSource().Index("source").Query(NewMatchQuery("company", "cat"))
- dst := NewReindexDestination().Index("dest").Routing("=cat")
- out, err := client.Reindex().Source(src).Destination(dst).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"dest":{"index":"dest","routing":"=cat"},"source":{"index":"source","query":{"match":{"company":{"query":"cat"}}}}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestReindex(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Reindex API yet", esversion)
- }
-
- sourceCount, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if sourceCount <= 0 {
- t.Fatalf("expected more than %d documents; got: %d", 0, sourceCount)
- }
-
- targetCount, err := client.Count(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if targetCount != 0 {
- t.Fatalf("expected %d documents; got: %d", 0, targetCount)
- }
-
- // Simple copying
- src := NewReindexSource().Index(testIndexName)
- dst := NewReindexDestination().Index(testIndexName2)
- res, err := client.Reindex().Source(src).Destination(dst).Refresh("true").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected result != nil")
- }
- if res.Total != sourceCount {
- t.Errorf("expected %d, got %d", sourceCount, res.Total)
- }
- if res.Updated != 0 {
- t.Errorf("expected %d, got %d", 0, res.Updated)
- }
- if res.Created != sourceCount {
- t.Errorf("expected %d, got %d", sourceCount, res.Created)
- }
-
- targetCount, err = client.Count(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if targetCount != sourceCount {
- t.Fatalf("expected %d documents; got: %d", sourceCount, targetCount)
- }
-}
-
-func TestReindexAsync(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Reindex API yet", esversion)
- }
-
- sourceCount, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if sourceCount <= 0 {
- t.Fatalf("expected more than %d documents; got: %d", 0, sourceCount)
- }
-
- targetCount, err := client.Count(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if targetCount != 0 {
- t.Fatalf("expected %d documents; got: %d", 0, targetCount)
- }
-
- // Simple copying
- src := NewReindexSource().Index(testIndexName)
- dst := NewReindexDestination().Index(testIndexName2)
- res, err := client.Reindex().Source(src).Destination(dst).DoAsync(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected result != nil")
- }
- if res.TaskId == "" {
- t.Errorf("expected a task id, got %+v", res)
- }
-
- tasksGetTask := client.TasksGetTask()
- taskStatus, err := tasksGetTask.TaskId(res.TaskId).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if taskStatus == nil {
- t.Fatal("expected task status result != nil")
- }
-}
-
-func TestReindexWithWaitForCompletionTrueCannotBeStarted(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Reindex API yet", esversion)
- }
-
- sourceCount, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if sourceCount <= 0 {
- t.Fatalf("expected more than %d documents; got: %d", 0, sourceCount)
- }
-
- targetCount, err := client.Count(testIndexName2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if targetCount != 0 {
- t.Fatalf("expected %d documents; got: %d", 0, targetCount)
- }
-
- // DoAsync should fail when WaitForCompletion is true
- src := NewReindexSource().Index(testIndexName)
- dst := NewReindexDestination().Index(testIndexName2)
- _, err = client.Reindex().Source(src).Destination(dst).WaitForCompletion(true).DoAsync(context.TODO())
- if err == nil {
- t.Fatal("error should have been returned")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/request.go b/vendor/gopkg.in/olivere/elastic.v5/request.go
index 87d191965..da5a7216e 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/request.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/request.go
@@ -6,6 +6,7 @@ package elastic
import (
"bytes"
+ "compress/gzip"
"encoding/json"
"io"
"io/ioutil"
@@ -34,13 +35,21 @@ func (r *Request) SetBasicAuth(username, password string) {
((*http.Request)(r)).SetBasicAuth(username, password)
}
-// SetBody encodes the body in the request.
-func (r *Request) SetBody(body interface{}) error {
+// SetBody encodes the body in the request. Optionally, it performs GZIP compression.
+func (r *Request) SetBody(body interface{}, gzipCompress bool) error {
switch b := body.(type) {
case string:
- return r.setBodyString(b)
+ if gzipCompress {
+ return r.setBodyGzip(b)
+ } else {
+ return r.setBodyString(b)
+ }
default:
- return r.setBodyJson(body)
+ if gzipCompress {
+ return r.setBodyGzip(body)
+ } else {
+ return r.setBodyJson(body)
+ }
}
}
@@ -60,6 +69,42 @@ func (r *Request) setBodyString(body string) error {
return r.setBodyReader(strings.NewReader(body))
}
+// setBodyGzip gzip's the body. It accepts both strings and structs as body.
+// The latter will be encoded via json.Marshal.
+func (r *Request) setBodyGzip(body interface{}) error {
+ switch b := body.(type) {
+ case string:
+ buf := new(bytes.Buffer)
+ w := gzip.NewWriter(buf)
+ if _, err := w.Write([]byte(b)); err != nil {
+ return err
+ }
+ if err := w.Close(); err != nil {
+ return err
+ }
+ r.Header.Add("Content-Encoding", "gzip")
+ r.Header.Add("Vary", "Accept-Encoding")
+ return r.setBodyReader(bytes.NewReader(buf.Bytes()))
+ default:
+ data, err := json.Marshal(b)
+ if err != nil {
+ return err
+ }
+ buf := new(bytes.Buffer)
+ w := gzip.NewWriter(buf)
+ if _, err := w.Write(data); err != nil {
+ return err
+ }
+ if err := w.Close(); err != nil {
+ return err
+ }
+ r.Header.Add("Content-Encoding", "gzip")
+ r.Header.Add("Vary", "Accept-Encoding")
+ r.Header.Set("Content-Type", "application/json")
+ return r.setBodyReader(bytes.NewReader(buf.Bytes()))
+ }
+}
+
// setBodyReader writes the body from an io.Reader.
func (r *Request) setBodyReader(body io.Reader) error {
rc, ok := body.(io.ReadCloser)
diff --git a/vendor/gopkg.in/olivere/elastic.v5/request_test.go b/vendor/gopkg.in/olivere/elastic.v5/request_test.go
deleted file mode 100644
index 04fbecbab..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/request_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-var testReq *Request // used as a temporary variable to avoid compiler optimizations in tests/benchmarks
-
-func TestRequestSetContentType(t *testing.T) {
- req, err := NewRequest("GET", "/")
- if err != nil {
- t.Fatal(err)
- }
- if want, have := "application/json", req.Header.Get("Content-Type"); want != have {
- t.Fatalf("want %q, have %q", want, have)
- }
- req.Header.Set("Content-Type", "application/x-ndjson")
- if want, have := "application/x-ndjson", req.Header.Get("Content-Type"); want != have {
- t.Fatalf("want %q, have %q", want, have)
- }
-}
-
-func BenchmarkRequestSetBodyString(b *testing.B) {
- req, err := NewRequest("GET", "/")
- if err != nil {
- b.Fatal(err)
- }
- for i := 0; i < b.N; i++ {
- body := `{"query":{"match_all":{}}}`
- err = req.SetBody(body)
- if err != nil {
- b.Fatal(err)
- }
- }
- testReq = req
-}
-
-func BenchmarkRequestSetBodyBytes(b *testing.B) {
- req, err := NewRequest("GET", "/")
- if err != nil {
- b.Fatal(err)
- }
- for i := 0; i < b.N; i++ {
- body := []byte(`{"query":{"match_all":{}}}`)
- err = req.SetBody(body)
- if err != nil {
- b.Fatal(err)
- }
- }
- testReq = req
-}
-
-func BenchmarkRequestSetBodyMap(b *testing.B) {
- req, err := NewRequest("GET", "/")
- if err != nil {
- b.Fatal(err)
- }
- for i := 0; i < b.N; i++ {
- body := map[string]interface{}{
- "query": map[string]interface{}{
- "match_all": map[string]interface{}{},
- },
- }
- err = req.SetBody(body)
- if err != nil {
- b.Fatal(err)
- }
- }
- testReq = req
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/response_test.go b/vendor/gopkg.in/olivere/elastic.v5/response_test.go
deleted file mode 100644
index e62773403..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/response_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "net/http"
- "testing"
-)
-
-func BenchmarkResponse(b *testing.B) {
- c := &Client{
- decoder: &DefaultDecoder{},
- }
-
- var resp *Response
- for n := 0; n < b.N; n++ {
- iteration := fmt.Sprint(n)
- body := fmt.Sprintf(`{"n":%d}`, n)
- res := &http.Response{
- Header: http.Header{
- "X-Iteration": []string{iteration},
- },
- Body: ioutil.NopCloser(bytes.NewBufferString(body)),
- StatusCode: http.StatusOK,
- }
- var err error
- resp, err = c.newResponse(res)
- if err != nil {
- b.Fatal(err)
- }
- /*
- if want, have := body, string(resp.Body); want != have {
- b.Fatalf("want %q, have %q", want, have)
- }
- //*/
- /*
- if want, have := iteration, resp.Header.Get("X-Iteration"); want != have {
- b.Fatalf("want %q, have %q", want, have)
- }
- //*/
- }
- _ = resp
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/retrier_test.go b/vendor/gopkg.in/olivere/elastic.v5/retrier_test.go
deleted file mode 100644
index c1c5ff524..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/retrier_test.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "errors"
- "net/http"
- "sync/atomic"
- "testing"
- "time"
-)
-
-type testRetrier struct {
- Retrier
- N int64
- Err error
-}
-
-func (r *testRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
- atomic.AddInt64(&r.N, 1)
- if r.Err != nil {
- return 0, false, r.Err
- }
- return r.Retrier.Retry(ctx, retry, req, resp, err)
-}
-
-func TestStopRetrier(t *testing.T) {
- r := NewStopRetrier()
- wait, ok, err := r.Retry(context.TODO(), 1, nil, nil, nil)
- if want, got := 0*time.Second, wait; want != got {
- t.Fatalf("expected %v, got %v", want, got)
- }
- if want, got := false, ok; want != got {
- t.Fatalf("expected %v, got %v", want, got)
- }
- if err != nil {
- t.Fatalf("expected nil, got %v", err)
- }
-}
-
-func TestRetrier(t *testing.T) {
- var numFailedReqs int
- fail := func(r *http.Request) (*http.Response, error) {
- numFailedReqs += 1
- //return &http.Response{Request: r, StatusCode: 400}, nil
- return nil, errors.New("request failed")
- }
-
- tr := &failingTransport{path: "/fail", fail: fail}
- httpClient := &http.Client{Transport: tr}
-
- retrier := &testRetrier{
- Retrier: NewBackoffRetrier(NewSimpleBackoff(100, 100, 100, 100, 100)),
- }
-
- client, err := NewClient(
- SetHttpClient(httpClient),
- SetMaxRetries(5),
- SetHealthcheck(false),
- SetRetrier(retrier))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/fail",
- })
- if err == nil {
- t.Fatal("expected error")
- }
- if res != nil {
- t.Fatal("expected no response")
- }
- // Connection should be marked as dead after it failed
- if numFailedReqs != 5 {
- t.Errorf("expected %d failed requests; got: %d", 5, numFailedReqs)
- }
- if retrier.N != 5 {
- t.Errorf("expected %d Retrier calls; got: %d", 5, retrier.N)
- }
-}
-
-func TestRetrierWithError(t *testing.T) {
- var numFailedReqs int
- fail := func(r *http.Request) (*http.Response, error) {
- numFailedReqs += 1
- //return &http.Response{Request: r, StatusCode: 400}, nil
- return nil, errors.New("request failed")
- }
-
- tr := &failingTransport{path: "/fail", fail: fail}
- httpClient := &http.Client{Transport: tr}
-
- kaboom := errors.New("kaboom")
- retrier := &testRetrier{
- Err: kaboom,
- Retrier: NewBackoffRetrier(NewSimpleBackoff(100, 100, 100, 100, 100)),
- }
-
- client, err := NewClient(
- SetHttpClient(httpClient),
- SetMaxRetries(5),
- SetHealthcheck(false),
- SetRetrier(retrier))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/fail",
- })
- if err != kaboom {
- t.Fatalf("expected %v, got %v", kaboom, err)
- }
- if res != nil {
- t.Fatal("expected no response")
- }
- if numFailedReqs != 1 {
- t.Errorf("expected %d failed requests; got: %d", 1, numFailedReqs)
- }
- if retrier.N != 1 {
- t.Errorf("expected %d Retrier calls; got: %d", 1, retrier.N)
- }
-}
-
-func TestRetrierOnPerformRequest(t *testing.T) {
- var numFailedReqs int
- fail := func(r *http.Request) (*http.Response, error) {
- numFailedReqs += 1
- //return &http.Response{Request: r, StatusCode: 400}, nil
- return nil, errors.New("request failed")
- }
-
- tr := &failingTransport{path: "/fail", fail: fail}
- httpClient := &http.Client{Transport: tr}
-
- defaultRetrier := &testRetrier{
- Retrier: NewStopRetrier(),
- }
- requestRetrier := &testRetrier{
- Retrier: NewStopRetrier(),
- }
-
- client, err := NewClient(
- SetHttpClient(httpClient),
- SetHealthcheck(false),
- SetRetrier(defaultRetrier))
- if err != nil {
- t.Fatal(err)
- }
-
- res, err := client.PerformRequest(context.TODO(), PerformRequestOptions{
- Method: "GET",
- Path: "/fail",
- Retrier: requestRetrier,
- })
- if err == nil {
- t.Fatal("expected error")
- }
- if res != nil {
- t.Fatal("expected no response")
- }
- if want, have := int64(0), defaultRetrier.N; want != have {
- t.Errorf("defaultRetrier: expected %d calls; got: %d", want, have)
- }
- if want, have := int64(1), requestRetrier.N; want != have {
- t.Errorf("requestRetrier: expected %d calls; got: %d", want, have)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/retry_test.go b/vendor/gopkg.in/olivere/elastic.v5/retry_test.go
deleted file mode 100644
index 804313095..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/retry_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-// This file is based on code that is (c) 2014 Cenk Altı and governed
-// by the MIT license.
-// See https://github.com/cenkalti/backoff for original source.
-
-package elastic
-
-import (
- "errors"
- "testing"
- "time"
-)
-
-func TestRetry(t *testing.T) {
- const successOn = 3
- var i = 0
-
- // This function is successfull on "successOn" calls.
- f := func() error {
- i++
- // t.Logf("function is called %d. time\n", i)
-
- if i == successOn {
- // t.Log("OK")
- return nil
- }
-
- // t.Log("error")
- return errors.New("error")
- }
-
- min := time.Duration(8) * time.Millisecond
- max := time.Duration(256) * time.Millisecond
- err := Retry(f, NewExponentialBackoff(min, max))
- if err != nil {
- t.Errorf("unexpected error: %s", err.Error())
- }
- if i != successOn {
- t.Errorf("invalid number of retries: %d", i)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/run-es.sh b/vendor/gopkg.in/olivere/elastic.v5/run-es.sh
index 624a864ed..b22e87675 100755
--- a/vendor/gopkg.in/olivere/elastic.v5/run-es.sh
+++ b/vendor/gopkg.in/olivere/elastic.v5/run-es.sh
@@ -1,3 +1,3 @@
#!/bin/sh
-VERSION=${VERSION:=6.2.1}
-docker run --rm -p 9200:9200 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" -e "bootstrap.memory_lock=true" -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch-oss:$VERSION elasticsearch -Enetwork.host=_local_,_site_ -Enetwork.publish_host=_local_
+VERSION=${VERSION:=5.6.8}
+docker run --rm --privileged=true -p 9200:9200 -p 9300:9300 -v "$PWD/etc:/usr/share/elasticsearch/config" -e "bootstrap.memory_lock=true" -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch:$VERSION elasticsearch -Expack.security.enabled=false -Expack.ml.enabled=false -Escript.inline=true -Escript.stored=true -Escript.file=true
diff --git a/vendor/gopkg.in/olivere/elastic.v5/script.go b/vendor/gopkg.in/olivere/elastic.v5/script.go
index 273473950..eb27f27f0 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/script.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/script.go
@@ -9,7 +9,7 @@ import "errors"
// Script holds all the paramaters necessary to compile or find in cache
// and then execute a script.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-scripting.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/modules-scripting.html
// for details of scripting.
type Script struct {
script string
@@ -22,21 +22,26 @@ type Script struct {
func NewScript(script string) *Script {
return &Script{
script: script,
- typ: "inline",
+ typ: "", // default type is "inline"
params: make(map[string]interface{}),
}
}
-// NewScriptInline creates and initializes a new inline script, i.e. code.
+// NewScriptInline creates and initializes a new Script of type "inline".
func NewScriptInline(script string) *Script {
return NewScript(script).Type("inline")
}
-// NewScriptStored creates and initializes a new stored script.
-func NewScriptStored(script string) *Script {
+// NewScriptId creates and initializes a new Script of type "id".
+func NewScriptId(script string) *Script {
return NewScript(script).Type("id")
}
+// NewScriptFile creates and initializes a new Script of type "file".
+func NewScriptFile(script string) *Script {
+ return NewScript(script).Type("file")
+}
+
// Script is either the cache key of the script to be compiled/executed
// or the actual script source code for inline scripts. For indexed
// scripts this is the id used in the request. For file scripts this is
@@ -46,7 +51,7 @@ func (s *Script) Script(script string) *Script {
return s
}
-// Type sets the type of script: "inline" or "id".
+// Type sets the type of script: "inline", "id", or "file".
func (s *Script) Type(typ string) *Script {
s.typ = typ
return s
@@ -55,7 +60,7 @@ func (s *Script) Type(typ string) *Script {
// Lang sets the language of the script. Permitted values are "groovy",
// "expression", "mustache", "mvel" (default), "javascript", "python".
// To use certain languages, you need to configure your server and/or
-// add plugins. See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-scripting.html
+// add plugins. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/modules-scripting.html
// for details.
func (s *Script) Lang(lang string) *Script {
s.lang = lang
@@ -79,22 +84,26 @@ func (s *Script) Params(params map[string]interface{}) *Script {
// Source returns the JSON serializable data for this Script.
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"
+
+ // In 5.5 and earlier, the type can "inline", "id", or "file".
+ // In 5.6+, the type can be "source", "id", or "file".
+ // So we use "inline" here to keep compatibility with 5.5 and earlier.
+ // Notice that this will trigger a deprecation warning in 5.6.
if s.typ == "" || s.typ == "inline" {
- source["source"] = s.script
+ source["inline"] = s.script
} else {
- source["id"] = s.script
+ // "id" or "file"
+ source[s.typ] = s.script
}
+
if s.lang != "" {
source["lang"] = s.lang
}
if len(s.params) > 0 {
source["params"] = s.params
}
+
return source, nil
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/script_test.go b/vendor/gopkg.in/olivere/elastic.v5/script_test.go
deleted file mode 100644
index aa475d7eb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/script_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestScriptingDefault(t *testing.T) {
- builder := NewScript("doc['field'].value * 2")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"source":"doc['field'].value * 2"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScriptingInline(t *testing.T) {
- builder := NewScriptInline("doc['field'].value * factor").Param("factor", 2.0)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"params":{"factor":2},"source":"doc['field'].value * factor"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScriptingStored(t *testing.T) {
- builder := NewScriptStored("script-with-id").Param("factor", 2.0)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"id":"script-with-id","params":{"factor":2}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/scroll.go b/vendor/gopkg.in/olivere/elastic.v5/scroll.go
index ac51a8c00..a34bbe6cb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/scroll.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/scroll.go
@@ -12,7 +12,7 @@ import (
"strings"
"sync"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
const (
@@ -100,7 +100,7 @@ func (s *ScrollService) Size(size int) *ScrollService {
// Body sets the raw body to send to Elasticsearch. This can be e.g. a string,
// a map[string]interface{} or anything that can be serialized into JSON.
// Notice that setting the body disables the use of SearchSource and many
-// other properties of the ScanService.
+// other properties of the SearchService.
func (s *ScrollService) Body(body interface{}) *ScrollService {
s.body = body
return s
@@ -125,7 +125,7 @@ func (s *ScrollService) Query(query Query) *ScrollService {
// PostFilter is executed as the last filter. It only affects the
// search hits but not facets. See
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-post-filter.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-post-filter.html
// for details.
func (s *ScrollService) PostFilter(postFilter Query) *ScrollService {
s.ss = s.ss.PostFilter(postFilter)
@@ -134,7 +134,7 @@ func (s *ScrollService) PostFilter(postFilter Query) *ScrollService {
// Slice allows slicing the scroll request into several batches.
// This is supported in Elasticsearch 5.0 or later.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html#sliced-scroll
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#sliced-scroll
// for details.
func (s *ScrollService) Slice(sliceQuery Query) *ScrollService {
s.ss = s.ss.Slice(sliceQuery)
@@ -155,7 +155,7 @@ func (s *ScrollService) FetchSourceContext(fetchSourceContext *FetchSourceContex
}
// Version can be set to true to return a version for each search hit.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-version.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-version.html.
func (s *ScrollService) Version(version bool) *ScrollService {
s.ss = s.ss.Version(version)
return s
@@ -266,7 +266,7 @@ func (s *ScrollService) Clear(ctx context.Context) error {
ScrollId: []string{scrollId},
}
- _, err := s.client.PerformRequest(ctx, PerformRequestOptions{
+ _, err := s.client.PerformRequestWithOptions(ctx, PerformRequestOptions{
Method: "DELETE",
Path: path,
Params: params,
@@ -297,7 +297,7 @@ func (s *ScrollService) first(ctx context.Context) (*SearchResult, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
+ res, err := s.client.PerformRequestWithOptions(ctx, PerformRequestOptions{
Method: "POST",
Path: path,
Params: params,
@@ -350,7 +350,7 @@ func (s *ScrollService) buildFirstURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.size != nil && *s.size > 0 {
params.Set("size", fmt.Sprintf("%d", *s.size))
@@ -417,7 +417,7 @@ func (s *ScrollService) next(ctx context.Context) (*SearchResult, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
+ res, err := s.client.PerformRequestWithOptions(ctx, PerformRequestOptions{
Method: "POST",
Path: path,
Params: params,
@@ -449,7 +449,7 @@ func (s *ScrollService) buildNextURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
return path, params, nil
diff --git a/vendor/gopkg.in/olivere/elastic.v5/scroll_test.go b/vendor/gopkg.in/olivere/elastic.v5/scroll_test.go
deleted file mode 100644
index c94e5f92f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/scroll_test.go
+++ /dev/null
@@ -1,387 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "io"
- _ "net/http"
- "testing"
-)
-
-func TestScroll(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Should return all documents. Just don't call Do yet!
- svc := client.Scroll(testIndexName).Size(1)
-
- pages := 0
- docs := 0
-
- for {
- res, err := svc.Do(context.TODO())
- if err == io.EOF {
- break
- }
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected results != nil; got nil")
- }
- if res.Hits == nil {
- t.Fatal("expected results.Hits != nil; got nil")
- }
- if want, have := int64(3), res.Hits.TotalHits; want != have {
- t.Fatalf("expected results.Hits.TotalHits = %d; got %d", want, have)
- }
- if want, have := 1, len(res.Hits.Hits); want != have {
- t.Fatalf("expected len(results.Hits.Hits) = %d; got %d", want, have)
- }
-
- pages++
-
- for _, hit := range res.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- docs++
- }
-
- if len(res.ScrollId) == 0 {
- t.Fatalf("expected scrollId in results; got %q", res.ScrollId)
- }
- }
-
- if want, have := 3, pages; want != have {
- t.Fatalf("expected to retrieve %d pages; got %d", want, have)
- }
- if want, have := 3, docs; want != have {
- t.Fatalf("expected to retrieve %d hits; got %d", want, have)
- }
-
- err = svc.Clear(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = svc.Do(context.TODO())
- if err == nil {
- t.Fatal("expected to fail")
- }
-}
-
-func TestScrollWithQueryAndSort(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- // client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Create a scroll service that returns tweets from user olivere
- // and returns them sorted by "message", in reverse order.
- //
- // Just don't call Do yet!
- svc := client.Scroll(testIndexName).
- Query(NewTermQuery("user", "olivere")).
- Sort("message", false).
- Size(1)
-
- docs := 0
- pages := 0
- for {
- res, err := svc.Do(context.TODO())
- if err == io.EOF {
- break
- }
- if err != nil {
- t.Fatal(err)
- }
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected results != nil; got nil")
- }
- if res.Hits == nil {
- t.Fatal("expected results.Hits != nil; got nil")
- }
- if want, have := int64(2), res.Hits.TotalHits; want != have {
- t.Fatalf("expected results.Hits.TotalHits = %d; got %d", want, have)
- }
- if want, have := 1, len(res.Hits.Hits); want != have {
- t.Fatalf("expected len(results.Hits.Hits) = %d; got %d", want, have)
- }
-
- pages++
-
- for _, hit := range res.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- docs++
- }
- }
-
- if want, have := 2, pages; want != have {
- t.Fatalf("expected to retrieve %d pages; got %d", want, have)
- }
- if want, have := 2, docs; want != have {
- t.Fatalf("expected to retrieve %d hits; got %d", want, have)
- }
-}
-
-func TestScrollWithBody(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndLog(t)
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch.", Retweets: 4}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic.", Retweets: 10}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun.", Retweets: 3}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Test with simple strings and a map
- var tests = []struct {
- Body interface{}
- ExpectedTotalHits int64
- ExpectedDocs int
- ExpectedPages int
- }{
- {
- Body: `{"query":{"match_all":{}}}`,
- ExpectedTotalHits: 3,
- ExpectedDocs: 3,
- ExpectedPages: 3,
- },
- {
- Body: `{"query":{"term":{"user":"olivere"}},"sort":["_doc"]}`,
- ExpectedTotalHits: 2,
- ExpectedDocs: 2,
- ExpectedPages: 2,
- },
- {
- Body: `{"query":{"term":{"user":"olivere"}},"sort":[{"retweets":"desc"}]}`,
- ExpectedTotalHits: 2,
- ExpectedDocs: 2,
- ExpectedPages: 2,
- },
- {
- Body: map[string]interface{}{
- "query": map[string]interface{}{
- "term": map[string]interface{}{
- "user": "olivere",
- },
- },
- "sort": []interface{}{"_doc"},
- },
- ExpectedTotalHits: 2,
- ExpectedDocs: 2,
- ExpectedPages: 2,
- },
- }
-
- for i, tt := range tests {
- // Should return all documents. Just don't call Do yet!
- svc := client.Scroll(testIndexName).Size(1).Body(tt.Body)
-
- pages := 0
- docs := 0
-
- for {
- res, err := svc.Do(context.TODO())
- if err == io.EOF {
- break
- }
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatalf("#%d: expected results != nil; got nil", i)
- }
- if res.Hits == nil {
- t.Fatalf("#%d: expected results.Hits != nil; got nil", i)
- }
- if want, have := tt.ExpectedTotalHits, res.Hits.TotalHits; want != have {
- t.Fatalf("#%d: expected results.Hits.TotalHits = %d; got %d", i, want, have)
- }
- if want, have := 1, len(res.Hits.Hits); want != have {
- t.Fatalf("#%d: expected len(results.Hits.Hits) = %d; got %d", i, want, have)
- }
-
- pages++
-
- for _, hit := range res.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("#%d: expected SearchResult.Hits.Hit.Index = %q; got %q", i, testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatalf("#%d: %v", i, err)
- }
- docs++
- }
-
- if len(res.ScrollId) == 0 {
- t.Fatalf("#%d: expected scrollId in results; got %q", i, res.ScrollId)
- }
- }
-
- if want, have := tt.ExpectedPages, pages; want != have {
- t.Fatalf("#%d: expected to retrieve %d pages; got %d", i, want, have)
- }
- if want, have := tt.ExpectedDocs, docs; want != have {
- t.Fatalf("#%d: expected to retrieve %d hits; got %d", i, want, have)
- }
-
- err = svc.Clear(context.TODO())
- if err != nil {
- t.Fatalf("#%d: failed to clear scroll context: %v", i, err)
- }
-
- _, err = svc.Do(context.TODO())
- if err == nil {
- t.Fatalf("#%d: expected to fail", i)
- }
- }
-}
-
-func TestScrollWithSlice(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- // Should return all documents. Just don't call Do yet!
- sliceQuery := NewSliceQuery().Id(0).Max(2)
- svc := client.Scroll(testIndexName).Slice(sliceQuery).Size(1)
-
- pages := 0
- docs := 0
-
- for {
- res, err := svc.Do(context.TODO())
- if err == io.EOF {
- break
- }
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected results != nil; got nil")
- }
- if res.Hits == nil {
- t.Fatal("expected results.Hits != nil; got nil")
- }
-
- pages++
-
- for _, hit := range res.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- docs++
- }
-
- if len(res.ScrollId) == 0 {
- t.Fatalf("expected scrollId in results; got %q", res.ScrollId)
- }
- }
-
- if pages == 0 {
- t.Fatal("expected to retrieve some pages")
- }
- if docs == 0 {
- t.Fatal("expected to retrieve some hits")
- }
-
- if err := svc.Clear(context.TODO()); err != nil {
- t.Fatal(err)
- }
-
- if _, err := svc.Do(context.TODO()); err == nil {
- t.Fatal("expected to fail")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search.go b/vendor/gopkg.in/olivere/elastic.v5/search.go
index 12d51bf1f..a9eb212f4 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search.go
@@ -12,7 +12,7 @@ import (
"reflect"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// Search for documents in Elasticsearch.
@@ -60,7 +60,7 @@ func (s *SearchService) Source(source interface{}) *SearchService {
// FilterPath allows reducing the response, a mechanism known as
// response filtering and described here:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/common-options.html#common-options-response-filtering.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/common-options.html#common-options-response-filtering.
func (s *SearchService) FilterPath(filterPath ...string) *SearchService {
s.filterPath = append(s.filterPath, filterPath...)
return s
@@ -110,10 +110,16 @@ func (s *SearchService) TimeoutInMillis(timeoutInMillis int) *SearchService {
return s
}
+// TerminateAfter specifies the maximum number of documents to collect for
+// each shard, upon reaching which the query execution will terminate early.
+func (s *SearchService) TerminateAfter(terminateAfter int) *SearchService {
+ s.searchSource = s.searchSource.TerminateAfter(terminateAfter)
+ return s
+}
+
// SearchType sets the search operation type. Valid values are:
-// "query_then_fetch", "query_and_fetch", "dfs_query_then_fetch",
-// "dfs_query_and_fetch", "count", "scan".
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-search-type.html
+// "dfs_query_then_fetch" and "query_then_fetch".
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-search-type.html
// for details.
func (s *SearchService) SearchType(searchType string) *SearchService {
s.searchType = searchType
@@ -278,7 +284,7 @@ func (s *SearchService) TrackScores(trackScores bool) *SearchService {
// SearchAfter allows a different form of pagination by using a live cursor,
// using the results of the previous page to help the retrieval of the next.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-search-after.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-search-after.html
func (s *SearchService) SearchAfter(sortValues ...interface{}) *SearchService {
s.searchSource = s.searchSource.SearchAfter(sortValues...)
return s
@@ -392,12 +398,7 @@ func (s *SearchService) Do(ctx context.Context) (*SearchResult, error) {
}
body = src
}
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -413,7 +414,7 @@ func (s *SearchService) Do(ctx context.Context) (*SearchResult, error) {
// SearchResult is the result of a search in Elasticsearch.
type SearchResult struct {
TookInMillis int64 `json:"took"` // search time in milliseconds
- ScrollId string `json:"_scroll_id"` // only used with Scroll and Scan operations
+ ScrollId string `json:"_scroll_id"` // only used with Scroll operations
Hits *SearchHits `json:"hits"` // the actual search hits
Suggest SearchSuggest `json:"suggest"` // results from suggesters
Aggregations Aggregations `json:"aggregations"` // results from aggregations
@@ -434,8 +435,7 @@ func (r *SearchResult) TotalHits() int64 {
// Each is a utility function to iterate over all hits. It saves you from
// checking for nil values. Notice that Each will ignore errors in
-// serializing JSON and hits with empty/nil _source will get an empty
-// value
+// serializing JSON.
func (r *SearchResult) Each(typ reflect.Type) []interface{} {
if r.Hits == nil || r.Hits.Hits == nil || len(r.Hits.Hits) == 0 {
return nil
@@ -490,7 +490,7 @@ type SearchHitInnerHits struct {
}
// SearchExplanation explains how the score for a hit was computed.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-explain.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-explain.html.
type SearchExplanation struct {
Value float64 `json:"value"` // e.g. 1.0
Description string `json:"description"` // e.g. "boost" or "ConstantScore(*:*), product of:"
@@ -500,11 +500,11 @@ type SearchExplanation struct {
// Suggest
// SearchSuggest is a map of suggestions.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-suggesters.html.
type SearchSuggest map[string][]SearchSuggestion
// SearchSuggestion is a single search suggestion.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-suggesters.html.
type SearchSuggestion struct {
Text string `json:"text"`
Offset int `json:"offset"`
@@ -513,7 +513,7 @@ type SearchSuggestion struct {
}
// SearchSuggestionOption is an option of a SearchSuggestion.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-suggesters.html.
type SearchSuggestionOption struct {
Text string `json:"text"`
Index string `json:"_index"`
@@ -576,6 +576,6 @@ type ProfileResult struct {
// Highlighting
// SearchHitHighlight is the highlight information of a search hit.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-highlighting.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-highlighting.html
// for a general discussion of highlighting.
type SearchHitHighlight map[string][]string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs.go
index 6359611b1..999a57d60 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs.go
@@ -13,7 +13,7 @@ import (
// analytic information over a set of documents. It is
// (in many senses) the follow-up of facets in Elasticsearch.
// For more details about aggregations, visit:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations.html
type Aggregation interface {
// Source returns a JSON-serializable aggregation that is a fragment
// of the request sent to Elasticsearch.
@@ -24,7 +24,7 @@ type Aggregation interface {
type Aggregations map[string]*json.RawMessage
// Min returns min aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-min-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-min-aggregation.html
func (a Aggregations) Min(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -39,7 +39,7 @@ func (a Aggregations) Min(name string) (*AggregationValueMetric, bool) {
}
// Max returns max aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-max-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-max-aggregation.html
func (a Aggregations) Max(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -54,7 +54,7 @@ func (a Aggregations) Max(name string) (*AggregationValueMetric, bool) {
}
// Sum returns sum aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-sum-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-sum-aggregation.html
func (a Aggregations) Sum(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -69,7 +69,7 @@ func (a Aggregations) Sum(name string) (*AggregationValueMetric, bool) {
}
// Avg returns average aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-avg-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-avg-aggregation.html
func (a Aggregations) Avg(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -84,7 +84,7 @@ func (a Aggregations) Avg(name string) (*AggregationValueMetric, bool) {
}
// ValueCount returns value-count aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-valuecount-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-valuecount-aggregation.html
func (a Aggregations) ValueCount(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -99,7 +99,7 @@ func (a Aggregations) ValueCount(name string) (*AggregationValueMetric, bool) {
}
// Cardinality returns cardinality aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-cardinality-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-cardinality-aggregation.html
func (a Aggregations) Cardinality(name string) (*AggregationValueMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationValueMetric)
@@ -114,7 +114,7 @@ func (a Aggregations) Cardinality(name string) (*AggregationValueMetric, bool) {
}
// Stats returns stats aggregation results.
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-stats-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-stats-aggregation.html
func (a Aggregations) Stats(name string) (*AggregationStatsMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationStatsMetric)
@@ -129,7 +129,7 @@ func (a Aggregations) Stats(name string) (*AggregationStatsMetric, bool) {
}
// ExtendedStats returns extended stats aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-extendedstats-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-extendedstats-aggregation.html
func (a Aggregations) ExtendedStats(name string) (*AggregationExtendedStatsMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationExtendedStatsMetric)
@@ -144,7 +144,7 @@ func (a Aggregations) ExtendedStats(name string) (*AggregationExtendedStatsMetri
}
// MatrixStats returns matrix stats aggregation results.
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-matrix-stats-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-matrix-stats-aggregation.html
func (a Aggregations) MatrixStats(name string) (*AggregationMatrixStats, bool) {
if raw, found := a[name]; found {
agg := new(AggregationMatrixStats)
@@ -159,7 +159,7 @@ func (a Aggregations) MatrixStats(name string) (*AggregationMatrixStats, bool) {
}
// Percentiles returns percentiles results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-percentile-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-aggregation.html
func (a Aggregations) Percentiles(name string) (*AggregationPercentilesMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPercentilesMetric)
@@ -174,7 +174,7 @@ func (a Aggregations) Percentiles(name string) (*AggregationPercentilesMetric, b
}
// PercentileRanks returns percentile ranks results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-percentile-rank-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-rank-aggregation.html
func (a Aggregations) PercentileRanks(name string) (*AggregationPercentilesMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPercentilesMetric)
@@ -189,7 +189,7 @@ func (a Aggregations) PercentileRanks(name string) (*AggregationPercentilesMetri
}
// TopHits returns top-hits aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-top-hits-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-top-hits-aggregation.html
func (a Aggregations) TopHits(name string) (*AggregationTopHitsMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationTopHitsMetric)
@@ -204,7 +204,7 @@ func (a Aggregations) TopHits(name string) (*AggregationTopHitsMetric, bool) {
}
// Global returns global results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-global-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-global-aggregation.html
func (a Aggregations) Global(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -219,7 +219,7 @@ func (a Aggregations) Global(name string) (*AggregationSingleBucket, bool) {
}
// Filter returns filter results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-filter-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filter-aggregation.html
func (a Aggregations) Filter(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -234,7 +234,7 @@ func (a Aggregations) Filter(name string) (*AggregationSingleBucket, bool) {
}
// Filters returns filters results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-filters-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filters-aggregation.html
func (a Aggregations) Filters(name string) (*AggregationBucketFilters, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketFilters)
@@ -248,8 +248,23 @@ func (a Aggregations) Filters(name string) (*AggregationBucketFilters, bool) {
return nil, false
}
+// AdjacencyMatrix returning a form of adjacency matrix.
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-adjacency-matrix-aggregation.html
+func (a Aggregations) AdjacencyMatrix(name string) (*AggregationBucketAdjacencyMatrix, bool) {
+ if raw, found := a[name]; found {
+ agg := new(AggregationBucketAdjacencyMatrix)
+ if raw == nil {
+ return agg, true
+ }
+ if err := json.Unmarshal(*raw, agg); err == nil {
+ return agg, true
+ }
+ }
+ return nil, false
+}
+
// Missing returns missing results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-missing-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-missing-aggregation.html
func (a Aggregations) Missing(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -264,7 +279,7 @@ func (a Aggregations) Missing(name string) (*AggregationSingleBucket, bool) {
}
// Nested returns nested results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-nested-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-nested-aggregation.html
func (a Aggregations) Nested(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -279,7 +294,7 @@ func (a Aggregations) Nested(name string) (*AggregationSingleBucket, bool) {
}
// ReverseNested returns reverse-nested results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-reverse-nested-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-reverse-nested-aggregation.html
func (a Aggregations) ReverseNested(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -294,7 +309,7 @@ func (a Aggregations) ReverseNested(name string) (*AggregationSingleBucket, bool
}
// Children returns children results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-children-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-children-aggregation.html
func (a Aggregations) Children(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -309,7 +324,7 @@ func (a Aggregations) Children(name string) (*AggregationSingleBucket, bool) {
}
// Terms returns terms aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-terms-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-terms-aggregation.html
func (a Aggregations) Terms(name string) (*AggregationBucketKeyItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketKeyItems)
@@ -324,7 +339,7 @@ func (a Aggregations) Terms(name string) (*AggregationBucketKeyItems, bool) {
}
// SignificantTerms returns significant terms aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html
func (a Aggregations) SignificantTerms(name string) (*AggregationBucketSignificantTerms, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketSignificantTerms)
@@ -339,7 +354,7 @@ func (a Aggregations) SignificantTerms(name string) (*AggregationBucketSignifica
}
// Sampler returns sampler aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-sampler-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-sampler-aggregation.html
func (a Aggregations) Sampler(name string) (*AggregationSingleBucket, bool) {
if raw, found := a[name]; found {
agg := new(AggregationSingleBucket)
@@ -353,8 +368,23 @@ func (a Aggregations) Sampler(name string) (*AggregationSingleBucket, bool) {
return nil, false
}
+// DiversifiedSampler returns diversified_sampler aggregation results.
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-diversified-sampler-aggregation.html
+func (a Aggregations) DiversifiedSampler(name string) (*AggregationSingleBucket, bool) {
+ if raw, found := a[name]; found {
+ agg := new(AggregationSingleBucket)
+ if raw == nil {
+ return agg, true
+ }
+ if err := json.Unmarshal(*raw, agg); err == nil {
+ return agg, true
+ }
+ }
+ return nil, false
+}
+
// Range returns range aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-range-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html
func (a Aggregations) Range(name string) (*AggregationBucketRangeItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketRangeItems)
@@ -369,7 +399,7 @@ func (a Aggregations) Range(name string) (*AggregationBucketRangeItems, bool) {
}
// KeyedRange returns keyed range aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-range-aggregation.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html.
func (a Aggregations) KeyedRange(name string) (*AggregationBucketKeyedRangeItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketKeyedRangeItems)
@@ -384,7 +414,7 @@ func (a Aggregations) KeyedRange(name string) (*AggregationBucketKeyedRangeItems
}
// DateRange returns date range aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-daterange-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-daterange-aggregation.html
func (a Aggregations) DateRange(name string) (*AggregationBucketRangeItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketRangeItems)
@@ -399,7 +429,7 @@ func (a Aggregations) DateRange(name string) (*AggregationBucketRangeItems, bool
}
// IPRange returns IP range aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-iprange-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-iprange-aggregation.html
func (a Aggregations) IPRange(name string) (*AggregationBucketRangeItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketRangeItems)
@@ -414,7 +444,7 @@ func (a Aggregations) IPRange(name string) (*AggregationBucketRangeItems, bool)
}
// Histogram returns histogram aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-histogram-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-histogram-aggregation.html
func (a Aggregations) Histogram(name string) (*AggregationBucketHistogramItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketHistogramItems)
@@ -429,7 +459,7 @@ func (a Aggregations) Histogram(name string) (*AggregationBucketHistogramItems,
}
// DateHistogram returns date histogram aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-datehistogram-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-datehistogram-aggregation.html
func (a Aggregations) DateHistogram(name string) (*AggregationBucketHistogramItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketHistogramItems)
@@ -444,7 +474,7 @@ func (a Aggregations) DateHistogram(name string) (*AggregationBucketHistogramIte
}
// GeoBounds returns geo-bounds aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-geobounds-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-geobounds-aggregation.html
func (a Aggregations) GeoBounds(name string) (*AggregationGeoBoundsMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationGeoBoundsMetric)
@@ -459,7 +489,7 @@ func (a Aggregations) GeoBounds(name string) (*AggregationGeoBoundsMetric, bool)
}
// GeoHash returns geo-hash aggregation results.
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-geohashgrid-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-geohashgrid-aggregation.html
func (a Aggregations) GeoHash(name string) (*AggregationBucketKeyItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketKeyItems)
@@ -473,8 +503,23 @@ func (a Aggregations) GeoHash(name string) (*AggregationBucketKeyItems, bool) {
return nil, false
}
+// GeoCentroid returns geo-centroid aggregation results.
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-metrics-geocentroid-aggregation.html
+func (a Aggregations) GeoCentroid(name string) (*AggregationGeoCentroidMetric, bool) {
+ if raw, found := a[name]; found {
+ agg := new(AggregationGeoCentroidMetric)
+ if raw == nil {
+ return agg, true
+ }
+ if err := json.Unmarshal(*raw, agg); err == nil {
+ return agg, true
+ }
+ }
+ return nil, false
+}
+
// GeoDistance returns geo distance aggregation results.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-geodistance-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-geodistance-aggregation.html
func (a Aggregations) GeoDistance(name string) (*AggregationBucketRangeItems, bool) {
if raw, found := a[name]; found {
agg := new(AggregationBucketRangeItems)
@@ -489,7 +534,7 @@ func (a Aggregations) GeoDistance(name string) (*AggregationBucketRangeItems, bo
}
// AvgBucket returns average bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-avg-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-avg-bucket-aggregation.html
func (a Aggregations) AvgBucket(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -504,7 +549,7 @@ func (a Aggregations) AvgBucket(name string) (*AggregationPipelineSimpleValue, b
}
// SumBucket returns sum bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-sum-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-sum-bucket-aggregation.html
func (a Aggregations) SumBucket(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -519,7 +564,7 @@ func (a Aggregations) SumBucket(name string) (*AggregationPipelineSimpleValue, b
}
// StatsBucket returns stats bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-stats-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-stats-bucket-aggregation.html
func (a Aggregations) StatsBucket(name string) (*AggregationPipelineStatsMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineStatsMetric)
@@ -534,7 +579,7 @@ func (a Aggregations) StatsBucket(name string) (*AggregationPipelineStatsMetric,
}
// PercentilesBucket returns stats bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-percentiles-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-percentiles-bucket-aggregation.html
func (a Aggregations) PercentilesBucket(name string) (*AggregationPipelinePercentilesMetric, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelinePercentilesMetric)
@@ -549,7 +594,7 @@ func (a Aggregations) PercentilesBucket(name string) (*AggregationPipelinePercen
}
// MaxBucket returns maximum bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-max-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-max-bucket-aggregation.html
func (a Aggregations) MaxBucket(name string) (*AggregationPipelineBucketMetricValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineBucketMetricValue)
@@ -564,7 +609,7 @@ func (a Aggregations) MaxBucket(name string) (*AggregationPipelineBucketMetricVa
}
// MinBucket returns minimum bucket pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-min-bucket-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-min-bucket-aggregation.html
func (a Aggregations) MinBucket(name string) (*AggregationPipelineBucketMetricValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineBucketMetricValue)
@@ -579,7 +624,7 @@ func (a Aggregations) MinBucket(name string) (*AggregationPipelineBucketMetricVa
}
// MovAvg returns moving average pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html
func (a Aggregations) MovAvg(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -594,7 +639,7 @@ func (a Aggregations) MovAvg(name string) (*AggregationPipelineSimpleValue, bool
}
// Derivative returns derivative pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-derivative-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-derivative-aggregation.html
func (a Aggregations) Derivative(name string) (*AggregationPipelineDerivative, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineDerivative)
@@ -609,7 +654,7 @@ func (a Aggregations) Derivative(name string) (*AggregationPipelineDerivative, b
}
// CumulativeSum returns a cumulative sum pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-cumulative-sum-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-cumulative-sum-aggregation.html
func (a Aggregations) CumulativeSum(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -624,7 +669,7 @@ func (a Aggregations) CumulativeSum(name string) (*AggregationPipelineSimpleValu
}
// BucketScript returns bucket script pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-bucket-script-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-script-aggregation.html
func (a Aggregations) BucketScript(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -639,7 +684,7 @@ func (a Aggregations) BucketScript(name string) (*AggregationPipelineSimpleValue
}
// SerialDiff returns serial differencing pipeline aggregation results.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-serialdiff-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-serialdiff-aggregation.html
func (a Aggregations) SerialDiff(name string) (*AggregationPipelineSimpleValue, bool) {
if raw, found := a[name]; found {
agg := new(AggregationPipelineSimpleValue)
@@ -653,23 +698,6 @@ func (a Aggregations) SerialDiff(name string) (*AggregationPipelineSimpleValue,
return nil, false
}
-// Composite returns composite bucket aggregation results.
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html
-// for details.
-func (a Aggregations) Composite(name string) (*AggregationBucketCompositeItems, bool) {
- if raw, found := a[name]; found {
- agg := new(AggregationBucketCompositeItems)
- if raw == nil {
- return agg, true
- }
- if err := json.Unmarshal(*raw, agg); err == nil {
- return agg, true
- }
- }
- return nil, false
-}
-
// -- Single value metric --
// AggregationValueMetric is a single-value metric, returned e.g. by a
@@ -922,6 +950,41 @@ func (a *AggregationGeoBoundsMetric) UnmarshalJSON(data []byte) error {
return nil
}
+// -- Geo Centroid --
+
+// AggregationGeocentroidMetric is a metric as returned by a GeoCentroid aggregation.
+type AggregationGeoCentroidMetric struct {
+ Aggregations
+
+ Location struct {
+ Latitude float64 `json:"lat"`
+ Longitude float64 `json:"lon"`
+ } `json:"location"`
+
+ Count int // `json:"count,omitempty"`
+
+ Meta map[string]interface{} // `json:"meta,omitempty"`
+}
+
+// UnmarshalJSON decodes JSON data and initializes an AggregationGeoCentroidMetric structure.
+func (a *AggregationGeoCentroidMetric) UnmarshalJSON(data []byte) error {
+ var aggs map[string]*json.RawMessage
+ if err := json.Unmarshal(data, &aggs); err != nil {
+ return err
+ }
+ if v, ok := aggs["location"]; ok && v != nil {
+ json.Unmarshal(*v, &a.Location)
+ }
+ if v, ok := aggs["meta"]; ok && v != nil {
+ json.Unmarshal(*v, &a.Meta)
+ }
+ if v, ok := aggs["count"]; ok && v != nil {
+ json.Unmarshal(*v, &a.Count)
+ }
+ a.Aggregations = aggs
+ return nil
+}
+
// -- Single bucket --
// AggregationSingleBucket is a single bucket, returned e.g. via an aggregation of type Global.
@@ -1215,6 +1278,33 @@ func (a *AggregationBucketFilters) UnmarshalJSON(data []byte) error {
return nil
}
+// -- Bucket AdjacencyMatrix --
+
+// AggregationBucketAdjacencyMatrix is a multi-bucket aggregation that is returned
+// with a AdjacencyMatrix aggregation.
+type AggregationBucketAdjacencyMatrix struct {
+ Aggregations
+
+ Buckets []*AggregationBucketKeyItem //`json:"buckets"`
+ Meta map[string]interface{} // `json:"meta,omitempty"`
+}
+
+// UnmarshalJSON decodes JSON data and initializes an AggregationBucketAdjacencyMatrix structure.
+func (a *AggregationBucketAdjacencyMatrix) UnmarshalJSON(data []byte) error {
+ var aggs map[string]*json.RawMessage
+ if err := json.Unmarshal(data, &aggs); err != nil {
+ return err
+ }
+ if v, ok := aggs["buckets"]; ok && v != nil {
+ json.Unmarshal(*v, &a.Buckets)
+ }
+ if v, ok := aggs["meta"]; ok && v != nil {
+ json.Unmarshal(*v, &a.Meta)
+ }
+ a.Aggregations = aggs
+ return nil
+}
+
// -- Bucket histogram items --
// AggregationBucketHistogramItems is a bucket aggregation that is returned
@@ -1465,56 +1555,3 @@ func (a *AggregationPipelinePercentilesMetric) UnmarshalJSON(data []byte) error
a.Aggregations = aggs
return nil
}
-
-// -- Composite key items --
-
-// AggregationBucketCompositeItems implements the response structure
-// for a bucket aggregation of type composite.
-type AggregationBucketCompositeItems struct {
- Aggregations
-
- Buckets []*AggregationBucketCompositeItem //`json:"buckets"`
- Meta map[string]interface{} // `json:"meta,omitempty"`
-}
-
-// UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItems structure.
-func (a *AggregationBucketCompositeItems) UnmarshalJSON(data []byte) error {
- var aggs map[string]*json.RawMessage
- if err := json.Unmarshal(data, &aggs); err != nil {
- return err
- }
- if v, ok := aggs["buckets"]; ok && v != nil {
- json.Unmarshal(*v, &a.Buckets)
- }
- if v, ok := aggs["meta"]; ok && v != nil {
- json.Unmarshal(*v, &a.Meta)
- }
- a.Aggregations = aggs
- return nil
-}
-
-// AggregationBucketCompositeItem is a single bucket of an AggregationBucketCompositeItems structure.
-type AggregationBucketCompositeItem struct {
- Aggregations
-
- Key map[string]interface{} //`json:"key"`
- DocCount int64 //`json:"doc_count"`
-}
-
-// UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItem structure.
-func (a *AggregationBucketCompositeItem) UnmarshalJSON(data []byte) error {
- var aggs map[string]*json.RawMessage
- dec := json.NewDecoder(bytes.NewReader(data))
- dec.UseNumber()
- if err := dec.Decode(&aggs); err != nil {
- return err
- }
- if v, ok := aggs["key"]; ok && v != nil {
- json.Unmarshal(*v, &a.Key)
- }
- if v, ok := aggs["doc_count"]; ok && v != nil {
- json.Unmarshal(*v, &a.DocCount)
- }
- a.Aggregations = aggs
- return nil
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_adjacency_matrix.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_adjacency_matrix.go
new file mode 100644
index 000000000..fa6e81464
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_adjacency_matrix.go
@@ -0,0 +1,96 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+// AdjacencyMatrixAggregation returning a form of adjacency matrix.
+// The request provides a collection of named filter expressions,
+// similar to the filters aggregation request. Each bucket in the
+// response represents a non-empty cell in the matrix of intersecting filters.
+//
+// For details, see
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-adjacency-matrix-aggregation.html
+type AdjacencyMatrixAggregation struct {
+ filters map[string]Query
+ subAggregations map[string]Aggregation
+ meta map[string]interface{}
+}
+
+// NewAdjacencyMatrixAggregation initializes a new AdjacencyMatrixAggregation.
+func NewAdjacencyMatrixAggregation() *AdjacencyMatrixAggregation {
+ return &AdjacencyMatrixAggregation{
+ filters: make(map[string]Query),
+ subAggregations: make(map[string]Aggregation),
+ }
+}
+
+// Filters adds the filter
+func (a *AdjacencyMatrixAggregation) Filters(name string, filter Query) *AdjacencyMatrixAggregation {
+ a.filters[name] = filter
+ return a
+}
+
+// SubAggregation adds a sub-aggregation to this aggregation.
+func (a *AdjacencyMatrixAggregation) SubAggregation(name string, subAggregation Aggregation) *AdjacencyMatrixAggregation {
+ a.subAggregations[name] = subAggregation
+ return a
+}
+
+// Meta sets the meta data to be included in the aggregation response.
+func (a *AdjacencyMatrixAggregation) Meta(metaData map[string]interface{}) *AdjacencyMatrixAggregation {
+ a.meta = metaData
+ return a
+}
+
+// Source returns the a JSON-serializable interface.
+func (a *AdjacencyMatrixAggregation) Source() (interface{}, error) {
+ // Example:
+ // {
+ // "aggs" : {
+ // "interactions" : {
+ // "adjacency_matrix" : {
+ // "filters" : {
+ // "grpA" : { "terms" : { "accounts" : ["hillary", "sidney"] }},
+ // "grpB" : { "terms" : { "accounts" : ["donald", "mitt"] }},
+ // "grpC" : { "terms" : { "accounts" : ["vladimir", "nigel"] }}
+ // }
+ // }
+ // }
+ // }
+ // This method returns only the (outer) { "adjacency_matrix" : {} } part.
+
+ source := make(map[string]interface{})
+ adjacencyMatrix := make(map[string]interface{})
+ source["adjacency_matrix"] = adjacencyMatrix
+
+ dict := make(map[string]interface{})
+ for key, filter := range a.filters {
+ src, err := filter.Source()
+ if err != nil {
+ return nil, err
+ }
+ dict[key] = src
+ }
+ adjacencyMatrix["filters"] = dict
+
+ // AggregationBuilder (SubAggregations)
+ if len(a.subAggregations) > 0 {
+ aggsMap := make(map[string]interface{})
+ source["aggregations"] = aggsMap
+ for name, aggregate := range a.subAggregations {
+ src, err := aggregate.Source()
+ if err != nil {
+ return nil, err
+ }
+ aggsMap[name] = src
+ }
+ }
+
+ // Add Meta data if available
+ if len(a.meta) > 0 {
+ source["meta"] = a.meta
+ }
+
+ return source, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children.go
index 08623a58e..14d0d1ca9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children.go
@@ -7,7 +7,7 @@ package elastic
// ChildrenAggregation is a special single bucket aggregation that enables
// aggregating from buckets on parent document types to buckets on child documents.
// It is available from 1.4.0.Beta1 upwards.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-children-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-children-aggregation.html
type ChildrenAggregation struct {
typ string
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children_test.go
deleted file mode 100644
index 0486079a9..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_children_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestChildrenAggregation(t *testing.T) {
- agg := NewChildrenAggregation().Type("answer")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"children":{"type":"answer"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestChildrenAggregationWithSubAggregation(t *testing.T) {
- subAgg := NewTermsAggregation().Field("owner.display_name").Size(10)
- agg := NewChildrenAggregation().Type("answer")
- agg = agg.SubAggregation("top-names", subAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"top-names":{"terms":{"field":"owner.display_name","size":10}}},"children":{"type":"answer"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite.go
deleted file mode 100644
index 1d9132d2d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite.go
+++ /dev/null
@@ -1,498 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-// CompositeAggregation is a multi-bucket values source based aggregation
-// that can be used to calculate unique composite values from source documents.
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html
-// for details.
-type CompositeAggregation struct {
- after map[string]interface{}
- size *int
- sources []CompositeAggregationValuesSource
- subAggregations map[string]Aggregation
- meta map[string]interface{}
-}
-
-// NewCompositeAggregation creates a new CompositeAggregation.
-func NewCompositeAggregation() *CompositeAggregation {
- return &CompositeAggregation{
- sources: make([]CompositeAggregationValuesSource, 0),
- subAggregations: make(map[string]Aggregation),
- }
-}
-
-// Size represents the number of composite buckets to return.
-// Defaults to 10 as of Elasticsearch 6.1.
-func (a *CompositeAggregation) Size(size int) *CompositeAggregation {
- a.size = &size
- return a
-}
-
-// AggregateAfter sets the values that indicate which composite bucket this
-// request should "aggregate after".
-func (a *CompositeAggregation) AggregateAfter(after map[string]interface{}) *CompositeAggregation {
- a.after = after
- return a
-}
-
-// Sources specifies the list of CompositeAggregationValuesSource instances to
-// use in the aggregation.
-func (a *CompositeAggregation) Sources(sources ...CompositeAggregationValuesSource) *CompositeAggregation {
- a.sources = append(a.sources, sources...)
- return a
-}
-
-// SubAggregations of this aggregation.
-func (a *CompositeAggregation) SubAggregation(name string, subAggregation Aggregation) *CompositeAggregation {
- a.subAggregations[name] = subAggregation
- return a
-}
-
-// Meta sets the meta data to be included in the aggregation response.
-func (a *CompositeAggregation) Meta(metaData map[string]interface{}) *CompositeAggregation {
- a.meta = metaData
- return a
-}
-
-// Source returns the serializable JSON for this aggregation.
-func (a *CompositeAggregation) Source() (interface{}, error) {
- // Example:
- // {
- // "aggs" : {
- // "my_composite_agg" : {
- // "composite" : {
- // "sources": [
- // {"my_term": { "terms": { "field": "product" }}},
- // {"my_histo": { "histogram": { "field": "price", "interval": 5 }}},
- // {"my_date": { "date_histogram": { "field": "timestamp", "interval": "1d" }}},
- // ],
- // "size" : 10,
- // "after" : ["a", 2, "c"]
- // }
- // }
- // }
- // }
- //
- // This method returns only the { "histogram" : { ... } } part.
-
- source := make(map[string]interface{})
- opts := make(map[string]interface{})
- source["composite"] = opts
-
- sources := make([]interface{}, len(a.sources))
- for i, s := range a.sources {
- src, err := s.Source()
- if err != nil {
- return nil, err
- }
- sources[i] = src
- }
- opts["sources"] = sources
-
- if a.size != nil {
- opts["size"] = *a.size
- }
-
- if a.after != nil {
- opts["after"] = a.after
- }
-
- // AggregationBuilder (SubAggregations)
- if len(a.subAggregations) > 0 {
- aggsMap := make(map[string]interface{})
- source["aggregations"] = aggsMap
- for name, aggregate := range a.subAggregations {
- src, err := aggregate.Source()
- if err != nil {
- return nil, err
- }
- aggsMap[name] = src
- }
- }
-
- // Add Meta data if available
- if len(a.meta) > 0 {
- source["meta"] = a.meta
- }
-
- return source, nil
-}
-
-// -- Generic interface for CompositeAggregationValues --
-
-// CompositeAggregationValuesSource specifies the interface that
-// all implementations for CompositeAggregation's Sources method
-// need to implement.
-//
-// The different implementations are described in
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html#_values_source_2.
-type CompositeAggregationValuesSource interface {
- Source() (interface{}, error)
-}
-
-// -- CompositeAggregationTermsValuesSource --
-
-// CompositeAggregationTermsValuesSource is a source for the CompositeAggregation that handles terms
-// it works very similar to a terms aggregation with slightly different syntax
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html#_terms
-// for details.
-type CompositeAggregationTermsValuesSource struct {
- name string
- field string
- script *Script
- valueType string
- missing interface{}
- order string
-}
-
-// NewCompositeAggregationTermsValuesSource creates and initializes
-// a new CompositeAggregationTermsValuesSource.
-func NewCompositeAggregationTermsValuesSource(name string) *CompositeAggregationTermsValuesSource {
- return &CompositeAggregationTermsValuesSource{
- name: name,
- }
-}
-
-// Field to use for this source.
-func (a *CompositeAggregationTermsValuesSource) Field(field string) *CompositeAggregationTermsValuesSource {
- a.field = field
- return a
-}
-
-// Script to use for this source.
-func (a *CompositeAggregationTermsValuesSource) Script(script *Script) *CompositeAggregationTermsValuesSource {
- a.script = script
- return a
-}
-
-// ValueType specifies the type of values produced by this source,
-// e.g. "string" or "date".
-func (a *CompositeAggregationTermsValuesSource) ValueType(valueType string) *CompositeAggregationTermsValuesSource {
- a.valueType = valueType
- return a
-}
-
-// Order specifies the order in the values produced by this source.
-// It can be either "asc" or "desc".
-func (a *CompositeAggregationTermsValuesSource) Order(order string) *CompositeAggregationTermsValuesSource {
- a.order = order
- return a
-}
-
-// Asc ensures the order of the values produced is ascending.
-func (a *CompositeAggregationTermsValuesSource) Asc() *CompositeAggregationTermsValuesSource {
- a.order = "asc"
- return a
-}
-
-// Desc ensures the order of the values produced is descending.
-func (a *CompositeAggregationTermsValuesSource) Desc() *CompositeAggregationTermsValuesSource {
- a.order = "desc"
- return a
-}
-
-// Missing specifies the value to use when the source finds a missing
-// value in a document.
-func (a *CompositeAggregationTermsValuesSource) Missing(missing interface{}) *CompositeAggregationTermsValuesSource {
- a.missing = missing
- return a
-}
-
-// Source returns the serializable JSON for this values source.
-func (a *CompositeAggregationTermsValuesSource) Source() (interface{}, error) {
- source := make(map[string]interface{})
- name := make(map[string]interface{})
- source[a.name] = name
- values := make(map[string]interface{})
- name["terms"] = values
-
- // field
- if a.field != "" {
- values["field"] = a.field
- }
-
- // script
- if a.script != nil {
- src, err := a.script.Source()
- if err != nil {
- return nil, err
- }
- values["script"] = src
- }
-
- // missing
- if a.missing != nil {
- values["missing"] = a.missing
- }
-
- // value_type
- if a.valueType != "" {
- values["value_type"] = a.valueType
- }
-
- // order
- if a.order != "" {
- values["order"] = a.order
- }
-
- return source, nil
-
-}
-
-// -- CompositeAggregationHistogramValuesSource --
-
-// CompositeAggregationHistogramValuesSource is a source for the CompositeAggregation that handles histograms
-// it works very similar to a terms histogram with slightly different syntax
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html#_histogram
-// for details.
-type CompositeAggregationHistogramValuesSource struct {
- name string
- field string
- script *Script
- valueType string
- missing interface{}
- order string
- interval float64
-}
-
-// NewCompositeAggregationHistogramValuesSource creates and initializes
-// a new CompositeAggregationHistogramValuesSource.
-func NewCompositeAggregationHistogramValuesSource(name string, interval float64) *CompositeAggregationHistogramValuesSource {
- return &CompositeAggregationHistogramValuesSource{
- name: name,
- interval: interval,
- }
-}
-
-// Field to use for this source.
-func (a *CompositeAggregationHistogramValuesSource) Field(field string) *CompositeAggregationHistogramValuesSource {
- a.field = field
- return a
-}
-
-// Script to use for this source.
-func (a *CompositeAggregationHistogramValuesSource) Script(script *Script) *CompositeAggregationHistogramValuesSource {
- a.script = script
- return a
-}
-
-// ValueType specifies the type of values produced by this source,
-// e.g. "string" or "date".
-func (a *CompositeAggregationHistogramValuesSource) ValueType(valueType string) *CompositeAggregationHistogramValuesSource {
- a.valueType = valueType
- return a
-}
-
-// Missing specifies the value to use when the source finds a missing
-// value in a document.
-func (a *CompositeAggregationHistogramValuesSource) Missing(missing interface{}) *CompositeAggregationHistogramValuesSource {
- a.missing = missing
- return a
-}
-
-// Order specifies the order in the values produced by this source.
-// It can be either "asc" or "desc".
-func (a *CompositeAggregationHistogramValuesSource) Order(order string) *CompositeAggregationHistogramValuesSource {
- a.order = order
- return a
-}
-
-// Asc ensures the order of the values produced is ascending.
-func (a *CompositeAggregationHistogramValuesSource) Asc() *CompositeAggregationHistogramValuesSource {
- a.order = "asc"
- return a
-}
-
-// Desc ensures the order of the values produced is descending.
-func (a *CompositeAggregationHistogramValuesSource) Desc() *CompositeAggregationHistogramValuesSource {
- a.order = "desc"
- return a
-}
-
-// Interval specifies the interval to use.
-func (a *CompositeAggregationHistogramValuesSource) Interval(interval float64) *CompositeAggregationHistogramValuesSource {
- a.interval = interval
- return a
-}
-
-// Source returns the serializable JSON for this values source.
-func (a *CompositeAggregationHistogramValuesSource) Source() (interface{}, error) {
- source := make(map[string]interface{})
- name := make(map[string]interface{})
- source[a.name] = name
- values := make(map[string]interface{})
- name["histogram"] = values
-
- // field
- if a.field != "" {
- values["field"] = a.field
- }
-
- // script
- if a.script != nil {
- src, err := a.script.Source()
- if err != nil {
- return nil, err
- }
- values["script"] = src
- }
-
- // missing
- if a.missing != nil {
- values["missing"] = a.missing
- }
-
- // value_type
- if a.valueType != "" {
- values["value_type"] = a.valueType
- }
-
- // order
- if a.order != "" {
- values["order"] = a.order
- }
-
- // Histogram-related properties
- values["interval"] = a.interval
-
- return source, nil
-
-}
-
-// -- CompositeAggregationDateHistogramValuesSource --
-
-// CompositeAggregationDateHistogramValuesSource is a source for the CompositeAggregation that handles date histograms
-// it works very similar to a date histogram aggregation with slightly different syntax
-//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-composite-aggregation.html#_date_histogram
-// for details.
-type CompositeAggregationDateHistogramValuesSource struct {
- name string
- field string
- script *Script
- valueType string
- missing interface{}
- order string
- interval interface{}
- timeZone string
-}
-
-// NewCompositeAggregationDateHistogramValuesSource creates and initializes
-// a new CompositeAggregationDateHistogramValuesSource.
-func NewCompositeAggregationDateHistogramValuesSource(name string, interval interface{}) *CompositeAggregationDateHistogramValuesSource {
- return &CompositeAggregationDateHistogramValuesSource{
- name: name,
- interval: interval,
- }
-}
-
-// Field to use for this source.
-func (a *CompositeAggregationDateHistogramValuesSource) Field(field string) *CompositeAggregationDateHistogramValuesSource {
- a.field = field
- return a
-}
-
-// Script to use for this source.
-func (a *CompositeAggregationDateHistogramValuesSource) Script(script *Script) *CompositeAggregationDateHistogramValuesSource {
- a.script = script
- return a
-}
-
-// ValueType specifies the type of values produced by this source,
-// e.g. "string" or "date".
-func (a *CompositeAggregationDateHistogramValuesSource) ValueType(valueType string) *CompositeAggregationDateHistogramValuesSource {
- a.valueType = valueType
- return a
-}
-
-// Missing specifies the value to use when the source finds a missing
-// value in a document.
-func (a *CompositeAggregationDateHistogramValuesSource) Missing(missing interface{}) *CompositeAggregationDateHistogramValuesSource {
- a.missing = missing
- return a
-}
-
-// Order specifies the order in the values produced by this source.
-// It can be either "asc" or "desc".
-func (a *CompositeAggregationDateHistogramValuesSource) Order(order string) *CompositeAggregationDateHistogramValuesSource {
- a.order = order
- return a
-}
-
-// Asc ensures the order of the values produced is ascending.
-func (a *CompositeAggregationDateHistogramValuesSource) Asc() *CompositeAggregationDateHistogramValuesSource {
- a.order = "asc"
- return a
-}
-
-// Desc ensures the order of the values produced is descending.
-func (a *CompositeAggregationDateHistogramValuesSource) Desc() *CompositeAggregationDateHistogramValuesSource {
- a.order = "desc"
- return a
-}
-
-// Interval to use for the date histogram, e.g. "1d" or a numeric value like "60".
-func (a *CompositeAggregationDateHistogramValuesSource) Interval(interval interface{}) *CompositeAggregationDateHistogramValuesSource {
- a.interval = interval
- return a
-}
-
-// TimeZone to use for the dates.
-func (a *CompositeAggregationDateHistogramValuesSource) TimeZone(timeZone string) *CompositeAggregationDateHistogramValuesSource {
- a.timeZone = timeZone
- return a
-}
-
-// Source returns the serializable JSON for this values source.
-func (a *CompositeAggregationDateHistogramValuesSource) Source() (interface{}, error) {
- source := make(map[string]interface{})
- name := make(map[string]interface{})
- source[a.name] = name
- values := make(map[string]interface{})
- name["date_histogram"] = values
-
- // field
- if a.field != "" {
- values["field"] = a.field
- }
-
- // script
- if a.script != nil {
- src, err := a.script.Source()
- if err != nil {
- return nil, err
- }
- values["script"] = src
- }
-
- // missing
- if a.missing != nil {
- values["missing"] = a.missing
- }
-
- // value_type
- if a.valueType != "" {
- values["value_type"] = a.valueType
- }
-
- // order
- if a.order != "" {
- values["order"] = a.order
- }
-
- // DateHistogram-related properties
- values["interval"] = a.interval
-
- // timeZone
- if a.timeZone != "" {
- values["time_zone"] = a.timeZone
- }
-
- return source, nil
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite_test.go
deleted file mode 100644
index 91d84dbdb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_composite_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestCompositeAggregation(t *testing.T) {
- agg := NewCompositeAggregation().
- Sources(
- NewCompositeAggregationTermsValuesSource("my_terms").Field("a_term").Missing("N/A").Order("asc"),
- NewCompositeAggregationHistogramValuesSource("my_histogram", 5).Field("price").Asc(),
- NewCompositeAggregationDateHistogramValuesSource("my_date_histogram", "1d").Field("purchase_date").Desc(),
- ).
- Size(10).
- AggregateAfter(map[string]interface{}{
- "my_terms": "1",
- "my_histogram": 2,
- "my_date_histogram": "3",
- })
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"composite":{"after":{"my_date_histogram":"3","my_histogram":2,"my_terms":"1"},"size":10,"sources":[{"my_terms":{"terms":{"field":"a_term","missing":"N/A","order":"asc"}}},{"my_histogram":{"histogram":{"field":"price","interval":5,"order":"asc"}}},{"my_date_histogram":{"date_histogram":{"field":"purchase_date","interval":"1d","order":"desc"}}}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompositeAggregationTermsValuesSource(t *testing.T) {
- in := NewCompositeAggregationTermsValuesSource("products").
- Script(NewScript("doc['product'].value").Lang("painless"))
- src, err := in.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"products":{"terms":{"script":{"lang":"painless","source":"doc['product'].value"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompositeAggregationHistogramValuesSource(t *testing.T) {
- in := NewCompositeAggregationHistogramValuesSource("histo", 5).
- Field("price")
- src, err := in.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"histo":{"histogram":{"field":"price","interval":5}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompositeAggregationDateHistogramValuesSource(t *testing.T) {
- in := NewCompositeAggregationDateHistogramValuesSource("date", "1d").
- Field("timestamp")
- src, err := in.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date":{"date_histogram":{"field":"timestamp","interval":"1d"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_count_thresholds.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_count_thresholds.go
deleted file mode 100644
index 53efdaf5f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_count_thresholds.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-// BucketCountThresholds is used in e.g. terms and significant text aggregations.
-type BucketCountThresholds struct {
- MinDocCount *int64
- ShardMinDocCount *int64
- RequiredSize *int
- ShardSize *int
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram.go
index 1e7a1246c..17916b490 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram.go
@@ -6,7 +6,7 @@ package elastic
// DateHistogramAggregation is a multi-bucket aggregation similar to the
// histogram except it can only be applied on date values.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-datehistogram-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-datehistogram-aggregation.html
type DateHistogramAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram_test.go
deleted file mode 100644
index ddf790834..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_histogram_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestDateHistogramAggregation(t *testing.T) {
- agg := NewDateHistogramAggregation().
- Field("date").
- Interval("month").
- Format("YYYY-MM").
- TimeZone("UTC").
- Offset("+6h")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_histogram":{"field":"date","format":"YYYY-MM","interval":"month","offset":"+6h","time_zone":"UTC"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateHistogramAggregationWithMissing(t *testing.T) {
- agg := NewDateHistogramAggregation().Field("date").Interval("year").Missing("1900")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_histogram":{"field":"date","interval":"year","missing":"1900"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range.go
index 714fd3e11..a4c10aa88 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range.go
@@ -15,7 +15,7 @@ import (
// date format by which the from and to response fields will be returned.
// Note that this aggregration includes the from value and excludes the to
// value for each range.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-daterange-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-daterange-aggregation.html
type DateRangeAggregation struct {
field string
script *Script
@@ -23,7 +23,6 @@ type DateRangeAggregation struct {
meta map[string]interface{}
keyed *bool
unmapped *bool
- timeZone string
format string
entries []DateRangeAggregationEntry
}
@@ -72,11 +71,6 @@ func (a *DateRangeAggregation) Unmapped(unmapped bool) *DateRangeAggregation {
return a
}
-func (a *DateRangeAggregation) TimeZone(timeZone string) *DateRangeAggregation {
- a.timeZone = timeZone
- return a
-}
-
func (a *DateRangeAggregation) Format(format string) *DateRangeAggregation {
a.format = format
return a
@@ -184,9 +178,6 @@ func (a *DateRangeAggregation) Source() (interface{}, error) {
if a.unmapped != nil {
opts["unmapped"] = *a.unmapped
}
- if a.timeZone != "" {
- opts["time_zone"] = a.timeZone
- }
if a.format != "" {
opts["format"] = a.format
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range_test.go
deleted file mode 100644
index 89ed495f3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_date_range_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestDateRangeAggregation(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").TimeZone("UTC")
- agg = agg.AddRange(nil, "2012-12-31")
- agg = agg.AddRange("2013-01-01", "2013-12-31")
- agg = agg.AddRange("2014-01-01", nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","ranges":[{"to":"2012-12-31"},{"from":"2013-01-01","to":"2013-12-31"},{"from":"2014-01-01"}],"time_zone":"UTC"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithPointers(t *testing.T) {
- d1 := "2012-12-31"
- d2 := "2013-01-01"
- d3 := "2013-12-31"
- d4 := "2014-01-01"
-
- agg := NewDateRangeAggregation().Field("created_at")
- agg = agg.AddRange(nil, &d1)
- agg = agg.AddRange(d2, &d3)
- agg = agg.AddRange(d4, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","ranges":[{"to":"2012-12-31"},{"from":"2013-01-01","to":"2013-12-31"},{"from":"2014-01-01"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithUnbounded(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").
- AddUnboundedFrom("2012-12-31").
- AddRange("2013-01-01", "2013-12-31").
- AddUnboundedTo("2014-01-01")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","ranges":[{"to":"2012-12-31"},{"from":"2013-01-01","to":"2013-12-31"},{"from":"2014-01-01"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithLtAndCo(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").
- Lt("2012-12-31").
- Between("2013-01-01", "2013-12-31").
- Gt("2014-01-01")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","ranges":[{"to":"2012-12-31"},{"from":"2013-01-01","to":"2013-12-31"},{"from":"2014-01-01"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithKeyedFlag(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").
- Keyed(true).
- Lt("2012-12-31").
- Between("2013-01-01", "2013-12-31").
- Gt("2014-01-01")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","keyed":true,"ranges":[{"to":"2012-12-31"},{"from":"2013-01-01","to":"2013-12-31"},{"from":"2014-01-01"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithKeys(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").
- Keyed(true).
- LtWithKey("pre-2012", "2012-12-31").
- BetweenWithKey("2013", "2013-01-01", "2013-12-31").
- GtWithKey("post-2013", "2014-01-01")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","keyed":true,"ranges":[{"key":"pre-2012","to":"2012-12-31"},{"from":"2013-01-01","key":"2013","to":"2013-12-31"},{"from":"2014-01-01","key":"post-2013"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestDateRangeAggregationWithSpecialNames(t *testing.T) {
- agg := NewDateRangeAggregation().Field("created_at").
- AddRange("now-10M/M", "now+10M/M")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"date_range":{"field":"created_at","ranges":[{"from":"now-10M/M","to":"now+10M/M"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_diversified_sampler.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_diversified_sampler.go
new file mode 100644
index 000000000..a70b83a2d
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_diversified_sampler.go
@@ -0,0 +1,126 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+// DiversifiedSamplerAggregation Like the ‘sampler` aggregation this is a filtering aggregation used to limit any
+// sub aggregations’ processing to a sample of the top-scoring documents. The diversified_sampler aggregation adds
+// the ability to limit the number of matches that share a common value such as an "author".
+//
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-diversified-sampler-aggregation.html
+type DiversifiedSamplerAggregation struct {
+ subAggregations map[string]Aggregation
+ meta map[string]interface{}
+ field string
+ script *Script
+ shardSize int
+ maxDocsPerValue int
+ executionHint string
+}
+
+func NewDiversifiedSamplerAggregation() *DiversifiedSamplerAggregation {
+ return &DiversifiedSamplerAggregation{
+ shardSize: -1,
+ maxDocsPerValue: -1,
+ subAggregations: make(map[string]Aggregation),
+ }
+}
+
+func (a *DiversifiedSamplerAggregation) SubAggregation(name string, subAggregation Aggregation) *DiversifiedSamplerAggregation {
+ a.subAggregations[name] = subAggregation
+ return a
+}
+
+// Meta sets the meta data to be included in the aggregation response.
+func (a *DiversifiedSamplerAggregation) Meta(metaData map[string]interface{}) *DiversifiedSamplerAggregation {
+ a.meta = metaData
+ return a
+}
+
+// Field on which the aggregation is processed.
+func (a *DiversifiedSamplerAggregation) Field(field string) *DiversifiedSamplerAggregation {
+ a.field = field
+ return a
+}
+
+func (a *DiversifiedSamplerAggregation) Script(script *Script) *DiversifiedSamplerAggregation {
+ a.script = script
+ return a
+}
+
+// ShardSize sets the maximum number of docs returned from each shard.
+func (a *DiversifiedSamplerAggregation) ShardSize(shardSize int) *DiversifiedSamplerAggregation {
+ a.shardSize = shardSize
+ return a
+}
+
+func (a *DiversifiedSamplerAggregation) MaxDocsPerValue(maxDocsPerValue int) *DiversifiedSamplerAggregation {
+ a.maxDocsPerValue = maxDocsPerValue
+ return a
+}
+
+func (a *DiversifiedSamplerAggregation) ExecutionHint(hint string) *DiversifiedSamplerAggregation {
+ a.executionHint = hint
+ return a
+}
+
+func (a *DiversifiedSamplerAggregation) Source() (interface{}, error) {
+ // Example:
+ // {
+ // "aggs": {
+ // "my_unbiased_sample": {
+ // "diversified_sampler": {
+ // "shard_size": 200,
+ // "field" : "author"
+ // }
+ // }
+ // }
+ // }
+ //
+ // This method returns only the { "diversified_sampler" : { ... } } part.
+
+ source := make(map[string]interface{})
+ opts := make(map[string]interface{})
+ source["diversified_sampler"] = opts
+
+ if a.field != "" {
+ opts["field"] = a.field
+ }
+ if a.script != nil {
+ src, err := a.script.Source()
+ if err != nil {
+ return nil, err
+ }
+ opts["script"] = src
+ }
+ if a.shardSize >= 0 {
+ opts["shard_size"] = a.shardSize
+ }
+ if a.maxDocsPerValue >= 0 {
+ opts["max_docs_per_value"] = a.maxDocsPerValue
+ }
+ if a.executionHint != "" {
+ opts["execution_hint"] = a.executionHint
+ }
+
+ // AggregationBuilder (SubAggregations)
+ if len(a.subAggregations) > 0 {
+ aggsMap := make(map[string]interface{})
+ source["aggregations"] = aggsMap
+ for name, aggregate := range a.subAggregations {
+ src, err := aggregate.Source()
+ if err != nil {
+ return nil, err
+ }
+ aggsMap[name] = src
+ }
+ }
+
+ // Add Meta data if available
+ if len(a.meta) > 0 {
+ source["meta"] = a.meta
+ }
+
+ return source, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter.go
index e4fbc67da..2085f0d36 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter.go
@@ -8,7 +8,7 @@ package elastic
// in the current document set context that match a specified filter.
// Often this will be used to narrow down the current aggregation context
// to a specific set of documents.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-filter-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filter-aggregation.html
type FilterAggregation struct {
filter Query
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter_test.go
deleted file mode 100644
index 6aa4fbb7c..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filter_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestFilterAggregation(t *testing.T) {
- filter := NewRangeQuery("stock").Gt(0)
- agg := NewFilterAggregation().Filter(filter)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filter":{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFilterAggregationWithSubAggregation(t *testing.T) {
- avgPriceAgg := NewAvgAggregation().Field("price")
- filter := NewRangeQuery("stock").Gt(0)
- agg := NewFilterAggregation().Filter(filter).
- SubAggregation("avg_price", avgPriceAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_price":{"avg":{"field":"price"}}},"filter":{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFilterAggregationWithMeta(t *testing.T) {
- filter := NewRangeQuery("stock").Gt(0)
- agg := NewFilterAggregation().Filter(filter).Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filter":{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters.go
index 0d128ca17..80999eed9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters.go
@@ -15,7 +15,7 @@ import "errors"
// use both named and unnamed filters.
//
// For details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-filters-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filters-aggregation.html
type FiltersAggregation struct {
unnamedFilters []Query
namedFilters map[string]Query
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters_test.go
deleted file mode 100644
index 95cc8d7c3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_filters_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestFiltersAggregationFilters(t *testing.T) {
- f1 := NewRangeQuery("stock").Gt(0)
- f2 := NewTermQuery("symbol", "GOOG")
- agg := NewFiltersAggregation().Filters(f1, f2)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFiltersAggregationFilterWithName(t *testing.T) {
- f1 := NewRangeQuery("stock").Gt(0)
- f2 := NewTermQuery("symbol", "GOOG")
- agg := NewFiltersAggregation().
- FilterWithName("f1", f1).
- FilterWithName("f2", f2)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filters":{"filters":{"f1":{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},"f2":{"term":{"symbol":"GOOG"}}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFiltersAggregationWithKeyedAndNonKeyedFilters(t *testing.T) {
- agg := NewFiltersAggregation().
- Filter(NewTermQuery("symbol", "MSFT")). // unnamed
- FilterWithName("one", NewTermQuery("symbol", "GOOG")) // named filter
- _, err := agg.Source()
- if err == nil {
- t.Fatal("expected error, got nil")
- }
-}
-
-func TestFiltersAggregationWithSubAggregation(t *testing.T) {
- avgPriceAgg := NewAvgAggregation().Field("price")
- f1 := NewRangeQuery("stock").Gt(0)
- f2 := NewTermQuery("symbol", "GOOG")
- agg := NewFiltersAggregation().Filters(f1, f2).SubAggregation("avg_price", avgPriceAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_price":{"avg":{"field":"price"}}},"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFiltersAggregationWithMetaData(t *testing.T) {
- f1 := NewRangeQuery("stock").Gt(0)
- f2 := NewTermQuery("symbol", "GOOG")
- agg := NewFiltersAggregation().Filters(f1, f2).Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance.go
index c082fb3f2..2ae7b63dc 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance.go
@@ -11,7 +11,7 @@ package elastic
// the origin point and determines the buckets it belongs to based on
// the ranges (a document belongs to a bucket if the distance between the
// document and the origin falls within the distance range of the bucket).
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-geodistance-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-geodistance-aggregation.html
type GeoDistanceAggregation struct {
field string
unit string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance_test.go
deleted file mode 100644
index 3918b9dd2..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geo_distance_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoDistanceAggregation(t *testing.T) {
- agg := NewGeoDistanceAggregation().Field("location").Point("52.3760, 4.894")
- agg = agg.AddRange(nil, 100)
- agg = agg.AddRange(100, 300)
- agg = agg.AddRange(300, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"field":"location","origin":"52.3760, 4.894","ranges":[{"to":100},{"from":100,"to":300},{"from":300}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceAggregationWithPointers(t *testing.T) {
- hundred := 100
- threeHundred := 300
- agg := NewGeoDistanceAggregation().Field("location").Point("52.3760, 4.894")
- agg = agg.AddRange(nil, &hundred)
- agg = agg.AddRange(hundred, &threeHundred)
- agg = agg.AddRange(threeHundred, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"field":"location","origin":"52.3760, 4.894","ranges":[{"to":100},{"from":100,"to":300},{"from":300}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceAggregationWithUnbounded(t *testing.T) {
- agg := NewGeoDistanceAggregation().Field("location").Point("52.3760, 4.894")
- agg = agg.AddUnboundedFrom(100)
- agg = agg.AddRange(100, 300)
- agg = agg.AddUnboundedTo(300)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"field":"location","origin":"52.3760, 4.894","ranges":[{"to":100},{"from":100,"to":300},{"from":300}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceAggregationWithMetaData(t *testing.T) {
- agg := NewGeoDistanceAggregation().Field("location").Point("52.3760, 4.894")
- agg = agg.AddRange(nil, 100)
- agg = agg.AddRange(100, 300)
- agg = agg.AddRange(300, nil)
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"field":"location","origin":"52.3760, 4.894","ranges":[{"to":100},{"from":100,"to":300},{"from":300}]},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geohash_grid_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geohash_grid_test.go
deleted file mode 100644
index 044e211eb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_geohash_grid_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoHashGridAggregation(t *testing.T) {
- agg := NewGeoHashGridAggregation().Field("location").Precision(5)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
-
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("Marshalling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geohash_grid":{"field":"location","precision":5}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoHashGridAggregationWithMetaData(t *testing.T) {
- agg := NewGeoHashGridAggregation().Field("location").Precision(5)
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
-
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("Marshalling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geohash_grid":{"field":"location","precision":5},"meta":{"name":"Oliver"}}`
-
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoHashGridAggregationWithSize(t *testing.T) {
- agg := NewGeoHashGridAggregation().Field("location").Precision(5).Size(5)
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
-
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("Marshalling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geohash_grid":{"field":"location","precision":5,"size":5},"meta":{"name":"Oliver"}}`
-
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoHashGridAggregationWithShardSize(t *testing.T) {
- agg := NewGeoHashGridAggregation().Field("location").Precision(5).ShardSize(5)
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
-
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("Marshalling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geohash_grid":{"field":"location","precision":5,"shard_size":5},"meta":{"name":"Oliver"}}`
-
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global.go
index 4bf2a63f8..fbd14a45f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global.go
@@ -8,7 +8,7 @@ package elastic
// the search execution context. This context is defined by the indices
// and the document types you’re searching on, but is not influenced
// by the search query itself.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-global-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-global-aggregation.html
type GlobalAggregation struct {
subAggregations map[string]Aggregation
meta map[string]interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global_test.go
deleted file mode 100644
index 5f1e5e6cb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_global_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGlobalAggregation(t *testing.T) {
- agg := NewGlobalAggregation()
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"global":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGlobalAggregationWithMetaData(t *testing.T) {
- agg := NewGlobalAggregation().Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"global":{},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram.go
index 8b698cff5..30528c164 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram.go
@@ -8,7 +8,7 @@ package elastic
// that can be applied on numeric values extracted from the documents.
// It dynamically builds fixed size (a.k.a. interval) buckets over the
// values.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-histogram-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-histogram-aggregation.html
type HistogramAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram_test.go
deleted file mode 100644
index aeb7eec54..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_histogram_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestHistogramAggregation(t *testing.T) {
- agg := NewHistogramAggregation().Field("price").Interval(50)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"histogram":{"field":"price","interval":50}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHistogramAggregationWithMetaData(t *testing.T) {
- agg := NewHistogramAggregation().Field("price").Offset(10).Interval(50).Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"histogram":{"field":"price","interval":50,"offset":10},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHistogramAggregationWithMissing(t *testing.T) {
- agg := NewHistogramAggregation().Field("price").Interval(50).Missing("n/a")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"histogram":{"field":"price","interval":50,"missing":"n/a"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range.go
index 3615e29c3..c32f334f3 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range.go
@@ -7,7 +7,7 @@ package elastic
// IPRangeAggregation is a range aggregation that is dedicated for
// IP addresses.
//
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-iprange-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-bucket-iprange-aggregation.html
type IPRangeAggregation struct {
field string
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range_test.go
deleted file mode 100644
index 7a2b49f4c..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_ip_range_test.go
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestIPRangeAggregation(t *testing.T) {
- agg := NewIPRangeAggregation().Field("remote_ip")
- agg = agg.AddRange("", "10.0.0.0")
- agg = agg.AddRange("10.1.0.0", "10.1.255.255")
- agg = agg.AddRange("10.2.0.0", "")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ip_range":{"field":"remote_ip","ranges":[{"to":"10.0.0.0"},{"from":"10.1.0.0","to":"10.1.255.255"},{"from":"10.2.0.0"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIPRangeAggregationMask(t *testing.T) {
- agg := NewIPRangeAggregation().Field("remote_ip")
- agg = agg.AddMaskRange("10.0.0.0/25")
- agg = agg.AddMaskRange("10.0.0.127/25")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ip_range":{"field":"remote_ip","ranges":[{"mask":"10.0.0.0/25"},{"mask":"10.0.0.127/25"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIPRangeAggregationWithKeyedFlag(t *testing.T) {
- agg := NewIPRangeAggregation().Field("remote_ip")
- agg = agg.Keyed(true)
- agg = agg.AddRange("", "10.0.0.0")
- agg = agg.AddRange("10.1.0.0", "10.1.255.255")
- agg = agg.AddRange("10.2.0.0", "")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ip_range":{"field":"remote_ip","keyed":true,"ranges":[{"to":"10.0.0.0"},{"from":"10.1.0.0","to":"10.1.255.255"},{"from":"10.2.0.0"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestIPRangeAggregationWithKeys(t *testing.T) {
- agg := NewIPRangeAggregation().Field("remote_ip")
- agg = agg.Keyed(true)
- agg = agg.LtWithKey("infinity", "10.0.0.5")
- agg = agg.GtWithKey("and-beyond", "10.0.0.5")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ip_range":{"field":"remote_ip","keyed":true,"ranges":[{"key":"infinity","to":"10.0.0.5"},{"from":"10.0.0.5","key":"and-beyond"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing.go
index 7ba3cb636..3ca3fd693 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing.go
@@ -11,7 +11,7 @@ package elastic
// conjunction with other field data bucket aggregators (such as ranges)
// to return information for all the documents that could not be placed
// in any of the other buckets due to missing field data values.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-missing-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-missing-aggregation.html
type MissingAggregation struct {
field string
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing_test.go
deleted file mode 100644
index 179c3084f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_missing_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMissingAggregation(t *testing.T) {
- agg := NewMissingAggregation().Field("price")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"missing":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMissingAggregationWithMetaData(t *testing.T) {
- agg := NewMissingAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"missing":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested.go
index 926d493a1..62e592eb8 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested.go
@@ -6,7 +6,7 @@ package elastic
// NestedAggregation is a special single bucket aggregation that enables
// aggregating nested documents.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-nested-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-nested-aggregation.html
type NestedAggregation struct {
path string
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested_test.go
deleted file mode 100644
index 219943e3d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_nested_test.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestNestedAggregation(t *testing.T) {
- agg := NewNestedAggregation().Path("resellers")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"nested":{"path":"resellers"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNestedAggregationWithSubAggregation(t *testing.T) {
- minPriceAgg := NewMinAggregation().Field("resellers.price")
- agg := NewNestedAggregation().Path("resellers").SubAggregation("min_price", minPriceAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"min_price":{"min":{"field":"resellers.price"}}},"nested":{"path":"resellers"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNestedAggregationWithMetaData(t *testing.T) {
- agg := NewNestedAggregation().Path("resellers").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"nested":{"path":"resellers"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go
index 28c3df78e..1c5204a0b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go
@@ -14,7 +14,7 @@ import (
// will be checked against each bucket range and "bucket" the
// relevant/matching document. Note that this aggregration includes the
// from value and excludes the to value for each range.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-range-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html
type RangeAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range_test.go
deleted file mode 100644
index 17fbcecf3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range_test.go
+++ /dev/null
@@ -1,178 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestRangeAggregation(t *testing.T) {
- agg := NewRangeAggregation().Field("price")
- agg = agg.AddRange(nil, 50)
- agg = agg.AddRange(50, 100)
- agg = agg.AddRange(100, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"price","ranges":[{"to":50},{"from":50,"to":100},{"from":100}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithPointers(t *testing.T) {
- fifty := 50
- hundred := 100
- agg := NewRangeAggregation().Field("price")
- agg = agg.AddRange(nil, &fifty)
- agg = agg.AddRange(fifty, &hundred)
- agg = agg.AddRange(hundred, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"price","ranges":[{"to":50},{"from":50,"to":100},{"from":100}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithUnbounded(t *testing.T) {
- agg := NewRangeAggregation().Field("field_name").
- AddUnboundedFrom(50).
- AddRange(20, 70).
- AddRange(70, 120).
- AddUnboundedTo(150)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"field_name","ranges":[{"to":50},{"from":20,"to":70},{"from":70,"to":120},{"from":150}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithLtAndCo(t *testing.T) {
- agg := NewRangeAggregation().Field("field_name").
- Lt(50).
- Between(20, 70).
- Between(70, 120).
- Gt(150)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"field_name","ranges":[{"to":50},{"from":20,"to":70},{"from":70,"to":120},{"from":150}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithKeyedFlag(t *testing.T) {
- agg := NewRangeAggregation().Field("field_name").
- Keyed(true).
- Lt(50).
- Between(20, 70).
- Between(70, 120).
- Gt(150)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"field_name","keyed":true,"ranges":[{"to":50},{"from":20,"to":70},{"from":70,"to":120},{"from":150}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithKeys(t *testing.T) {
- agg := NewRangeAggregation().Field("field_name").
- Keyed(true).
- LtWithKey("cheap", 50).
- BetweenWithKey("affordable", 20, 70).
- BetweenWithKey("average", 70, 120).
- GtWithKey("expensive", 150)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"field_name","keyed":true,"ranges":[{"key":"cheap","to":50},{"from":20,"key":"affordable","to":70},{"from":70,"key":"average","to":120},{"from":150,"key":"expensive"}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithMetaData(t *testing.T) {
- agg := NewRangeAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- agg = agg.AddRange(nil, 50)
- agg = agg.AddRange(50, 100)
- agg = agg.AddRange(100, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"range":{"field":"price","ranges":[{"to":50},{"from":50,"to":100},{"from":100}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeAggregationWithMissing(t *testing.T) {
- agg := NewRangeAggregation().Field("price").Missing(0)
- agg = agg.AddRange(nil, 50)
- agg = agg.AddRange(50, 100)
- agg = agg.AddRange(100, nil)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"field":"price","missing":0,"ranges":[{"to":50},{"from":50,"to":100},{"from":100}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested.go
index 9e4680195..f307f256f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested.go
@@ -11,7 +11,7 @@ package elastic
// which allows nesting other aggregations that aren’t part of
// the nested object in a nested aggregation.
//
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-reverse-nested-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-reverse-nested-aggregation.html
type ReverseNestedAggregation struct {
path string
subAggregations map[string]Aggregation
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested_test.go
deleted file mode 100644
index dc50bbc28..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_reverse_nested_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestReverseNestedAggregation(t *testing.T) {
- agg := NewReverseNestedAggregation()
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"reverse_nested":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestReverseNestedAggregationWithPath(t *testing.T) {
- agg := NewReverseNestedAggregation().Path("comments")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"reverse_nested":{"path":"comments"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestReverseNestedAggregationWithSubAggregation(t *testing.T) {
- avgPriceAgg := NewAvgAggregation().Field("price")
- agg := NewReverseNestedAggregation().
- Path("a_path").
- SubAggregation("avg_price", avgPriceAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_price":{"avg":{"field":"price"}}},"reverse_nested":{"path":"a_path"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestReverseNestedAggregationWithMeta(t *testing.T) {
- agg := NewReverseNestedAggregation().
- Path("a_path").
- Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"reverse_nested":{"path":"a_path"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler.go
index 0fd729dfd..c1a1ab4f7 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler.go
@@ -9,7 +9,7 @@ package elastic
// Optionally, diversity settings can be used to limit the number of matches
// that share a common value such as an "author".
//
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-sampler-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-sampler-aggregation.html
type SamplerAggregation struct {
subAggregations map[string]Aggregation
meta map[string]interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler_test.go
deleted file mode 100644
index c4dc1c7cc..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_sampler_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSamplerAggregation(t *testing.T) {
- keywordsAgg := NewSignificantTermsAggregation().Field("text")
- agg := NewSamplerAggregation().
- ShardSize(200).
- SubAggregation("keywords", keywordsAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"keywords":{"significant_terms":{"field":"text"}}},"sampler":{"shard_size":200}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms.go
index 571a91217..e03801f1e 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms.go
@@ -4,9 +4,9 @@
package elastic
-// SignificantTermsAggregation is an aggregation that returns interesting
+// SignificantSignificantTermsAggregation is an aggregation that returns interesting
// or unusual occurrences of terms in a set.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html
type SignificantTermsAggregation struct {
field string
subAggregations map[string]Aggregation
@@ -166,7 +166,7 @@ type SignificanceHeuristic interface {
// ChiSquareSignificanceHeuristic implements Chi square as described
// in "Information Retrieval", Manning et al., Chapter 13.5.2.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_chi_square
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_chi_square
// for details.
type ChiSquareSignificanceHeuristic struct {
backgroundIsSuperset *bool
@@ -216,7 +216,7 @@ func (sh *ChiSquareSignificanceHeuristic) Source() (interface{}, error) {
// as described in "The Google Similarity Distance", Cilibrasi and Vitanyi,
// 2007.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_google_normalized_distance
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_google_normalized_distance
// for details.
type GNDSignificanceHeuristic struct {
backgroundIsSuperset *bool
@@ -252,7 +252,7 @@ func (sh *GNDSignificanceHeuristic) Source() (interface{}, error) {
// -- JLH Score --
// JLHScoreSignificanceHeuristic implements the JLH score as described in
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_jlh_score.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_jlh_score.
type JLHScoreSignificanceHeuristic struct{}
// NewJLHScoreSignificanceHeuristic initializes a new JLHScoreSignificanceHeuristic.
@@ -276,7 +276,7 @@ func (sh *JLHScoreSignificanceHeuristic) Source() (interface{}, error) {
// MutualInformationSignificanceHeuristic implements Mutual information
// as described in "Information Retrieval", Manning et al., Chapter 13.5.1.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_mutual_information
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_mutual_information
// for details.
type MutualInformationSignificanceHeuristic struct {
backgroundIsSuperset *bool
@@ -324,7 +324,7 @@ func (sh *MutualInformationSignificanceHeuristic) Source() (interface{}, error)
// -- Percentage Score --
// PercentageScoreSignificanceHeuristic implements the algorithm described
-// in https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_percentage.
+// in https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_percentage.
type PercentageScoreSignificanceHeuristic struct{}
// NewPercentageScoreSignificanceHeuristic initializes a new instance of
@@ -347,7 +347,7 @@ func (sh *PercentageScoreSignificanceHeuristic) Source() (interface{}, error) {
// -- Script --
// ScriptSignificanceHeuristic implements a scripted significance heuristic.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_scripted
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_scripted
// for details.
type ScriptSignificanceHeuristic struct {
script *Script
@@ -368,7 +368,7 @@ func (sh *ScriptSignificanceHeuristic) Name() string {
// parameters are available in the script: `_subset_freq`, `_superset_freq`,
// `_subset_size`, and `_superset_size`.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significantterms-aggregation.html#_scripted
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_scripted
// for details.
func (sh *ScriptSignificanceHeuristic) Script(script *Script) *ScriptSignificanceHeuristic {
sh.script = script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms_test.go
deleted file mode 100644
index a5b269671..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_terms_test.go
+++ /dev/null
@@ -1,211 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSignificantTermsAggregation(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithArgs(t *testing.T) {
- agg := NewSignificantTermsAggregation().
- Field("crime_type").
- ExecutionHint("map").
- ShardSize(5).
- MinDocCount(10).
- BackgroundFilter(NewTermQuery("city", "London"))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"background_filter":{"term":{"city":"London"}},"execution_hint":"map","field":"crime_type","min_doc_count":10,"shard_size":5}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationSubAggregation(t *testing.T) {
- crimeTypesAgg := NewSignificantTermsAggregation().Field("crime_type")
- agg := NewTermsAggregation().Field("force")
- agg = agg.SubAggregation("significantCrimeTypes", crimeTypesAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"significantCrimeTypes":{"significant_terms":{"field":"crime_type"}}},"terms":{"field":"force"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithMetaData(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"significant_terms":{"field":"crime_type"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithChiSquare(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewChiSquareSignificanceHeuristic().
- BackgroundIsSuperset(true).
- IncludeNegatives(false),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"chi_square":{"background_is_superset":true,"include_negatives":false},"field":"crime_type"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithGND(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewGNDSignificanceHeuristic(),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type","gnd":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithJLH(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewJLHScoreSignificanceHeuristic(),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type","jlh":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithMutualInformation(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewMutualInformationSignificanceHeuristic().
- BackgroundIsSuperset(false).
- IncludeNegatives(true),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type","mutual_information":{"background_is_superset":false,"include_negatives":true}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithPercentageScore(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewPercentageScoreSignificanceHeuristic(),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type","percentage":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTermsAggregationWithScript(t *testing.T) {
- agg := NewSignificantTermsAggregation().Field("crime_type")
- agg = agg.SignificanceHeuristic(
- NewScriptSignificanceHeuristic().
- Script(NewScript("_subset_freq/(_superset_freq - _subset_freq + 1)")),
- )
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_terms":{"field":"crime_type","script_heuristic":{"script":{"source":"_subset_freq/(_superset_freq - _subset_freq + 1)"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text.go
deleted file mode 100644
index de761613c..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text.go
+++ /dev/null
@@ -1,245 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-// SignificantTextAggregation returns interesting or unusual occurrences
-// of free-text terms in a set.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-bucket-significanttext-aggregation.html
-type SignificantTextAggregation struct {
- field string
- subAggregations map[string]Aggregation
- meta map[string]interface{}
-
- sourceFieldNames []string
- filterDuplicateText *bool
- includeExclude *TermsAggregationIncludeExclude
- filter Query
- bucketCountThresholds *BucketCountThresholds
- significanceHeuristic SignificanceHeuristic
-}
-
-func NewSignificantTextAggregation() *SignificantTextAggregation {
- return &SignificantTextAggregation{
- subAggregations: make(map[string]Aggregation, 0),
- }
-}
-
-func (a *SignificantTextAggregation) Field(field string) *SignificantTextAggregation {
- a.field = field
- return a
-}
-
-func (a *SignificantTextAggregation) SubAggregation(name string, subAggregation Aggregation) *SignificantTextAggregation {
- a.subAggregations[name] = subAggregation
- return a
-}
-
-// Meta sets the meta data to be included in the aggregation response.
-func (a *SignificantTextAggregation) Meta(metaData map[string]interface{}) *SignificantTextAggregation {
- a.meta = metaData
- return a
-}
-
-func (a *SignificantTextAggregation) SourceFieldNames(names ...string) *SignificantTextAggregation {
- a.sourceFieldNames = names
- return a
-}
-
-func (a *SignificantTextAggregation) FilterDuplicateText(filter bool) *SignificantTextAggregation {
- a.filterDuplicateText = &filter
- return a
-}
-
-func (a *SignificantTextAggregation) MinDocCount(minDocCount int64) *SignificantTextAggregation {
- if a.bucketCountThresholds == nil {
- a.bucketCountThresholds = &BucketCountThresholds{}
- }
- a.bucketCountThresholds.MinDocCount = &minDocCount
- return a
-}
-
-func (a *SignificantTextAggregation) ShardMinDocCount(shardMinDocCount int64) *SignificantTextAggregation {
- if a.bucketCountThresholds == nil {
- a.bucketCountThresholds = &BucketCountThresholds{}
- }
- a.bucketCountThresholds.ShardMinDocCount = &shardMinDocCount
- return a
-}
-
-func (a *SignificantTextAggregation) Size(size int) *SignificantTextAggregation {
- if a.bucketCountThresholds == nil {
- a.bucketCountThresholds = &BucketCountThresholds{}
- }
- a.bucketCountThresholds.RequiredSize = &size
- return a
-}
-
-func (a *SignificantTextAggregation) ShardSize(shardSize int) *SignificantTextAggregation {
- if a.bucketCountThresholds == nil {
- a.bucketCountThresholds = &BucketCountThresholds{}
- }
- a.bucketCountThresholds.ShardSize = &shardSize
- return a
-}
-
-func (a *SignificantTextAggregation) BackgroundFilter(filter Query) *SignificantTextAggregation {
- a.filter = filter
- return a
-}
-
-func (a *SignificantTextAggregation) SignificanceHeuristic(heuristic SignificanceHeuristic) *SignificantTextAggregation {
- a.significanceHeuristic = heuristic
- return a
-}
-
-func (a *SignificantTextAggregation) Include(regexp string) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.Include = regexp
- return a
-}
-
-func (a *SignificantTextAggregation) IncludeValues(values ...interface{}) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.IncludeValues = append(a.includeExclude.IncludeValues, values...)
- return a
-}
-
-func (a *SignificantTextAggregation) Exclude(regexp string) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.Exclude = regexp
- return a
-}
-
-func (a *SignificantTextAggregation) ExcludeValues(values ...interface{}) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.ExcludeValues = append(a.includeExclude.ExcludeValues, values...)
- return a
-}
-
-func (a *SignificantTextAggregation) Partition(p int) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.Partition = p
- return a
-}
-
-func (a *SignificantTextAggregation) NumPartitions(n int) *SignificantTextAggregation {
- if a.includeExclude == nil {
- a.includeExclude = &TermsAggregationIncludeExclude{}
- }
- a.includeExclude.NumPartitions = n
- return a
-}
-
-func (a *SignificantTextAggregation) Source() (interface{}, error) {
- // Example:
- // {
- // "query" : {
- // "match" : {"content" : "Bird flu"}
- // },
- // "aggregations" : {
- // "my_sample" : {
- // "sampler": {
- // "shard_size" : 100
- // },
- // "aggregations": {
- // "keywords" : {
- // "significant_text" : { "field" : "content" }
- // }
- // }
- // }
- // }
- // }
- //
- // This method returns only the
- // { "significant_text" : { "field" : "content" }
- // part.
-
- source := make(map[string]interface{})
- opts := make(map[string]interface{})
- source["significant_text"] = opts
-
- if a.field != "" {
- opts["field"] = a.field
- }
- if a.bucketCountThresholds != nil {
- if a.bucketCountThresholds.RequiredSize != nil {
- opts["size"] = (*a.bucketCountThresholds).RequiredSize
- }
- if a.bucketCountThresholds.ShardSize != nil {
- opts["shard_size"] = (*a.bucketCountThresholds).ShardSize
- }
- if a.bucketCountThresholds.MinDocCount != nil {
- opts["min_doc_count"] = (*a.bucketCountThresholds).MinDocCount
- }
- if a.bucketCountThresholds.ShardMinDocCount != nil {
- opts["shard_min_doc_count"] = (*a.bucketCountThresholds).ShardMinDocCount
- }
- }
- if a.filter != nil {
- src, err := a.filter.Source()
- if err != nil {
- return nil, err
- }
- opts["background_filter"] = src
- }
- if a.significanceHeuristic != nil {
- name := a.significanceHeuristic.Name()
- src, err := a.significanceHeuristic.Source()
- if err != nil {
- return nil, err
- }
- opts[name] = src
- }
- // Include/Exclude
- if ie := a.includeExclude; ie != nil {
- // Include
- if ie.Include != "" {
- opts["include"] = ie.Include
- } else if len(ie.IncludeValues) > 0 {
- opts["include"] = ie.IncludeValues
- } else if ie.NumPartitions > 0 {
- inc := make(map[string]interface{})
- inc["partition"] = ie.Partition
- inc["num_partitions"] = ie.NumPartitions
- opts["include"] = inc
- }
- // Exclude
- if ie.Exclude != "" {
- opts["exclude"] = ie.Exclude
- } else if len(ie.ExcludeValues) > 0 {
- opts["exclude"] = ie.ExcludeValues
- }
- }
-
- // AggregationBuilder (SubAggregations)
- if len(a.subAggregations) > 0 {
- aggsMap := make(map[string]interface{})
- source["aggregations"] = aggsMap
- for name, aggregate := range a.subAggregations {
- src, err := aggregate.Source()
- if err != nil {
- return nil, err
- }
- aggsMap[name] = src
- }
- }
-
- // Add Meta data if available
- if len(a.meta) > 0 {
- source["meta"] = a.meta
- }
-
- return source, nil
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text_test.go
deleted file mode 100644
index 53ac4461d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_significant_text_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSignificantTextAggregation(t *testing.T) {
- agg := NewSignificantTextAggregation().Field("content")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_text":{"field":"content"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTextAggregationWithArgs(t *testing.T) {
- agg := NewSignificantTextAggregation().
- Field("content").
- ShardSize(5).
- MinDocCount(10).
- BackgroundFilter(NewTermQuery("city", "London"))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"significant_text":{"background_filter":{"term":{"city":"London"}},"field":"content","min_doc_count":10,"shard_size":5}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSignificantTextAggregationWithMetaData(t *testing.T) {
- agg := NewSignificantTextAggregation().Field("content")
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"significant_text":{"field":"content"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_terms_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_terms_test.go
deleted file mode 100644
index 351cbf63b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_terms_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTermsAggregation(t *testing.T) {
- agg := NewTermsAggregation().Field("gender").Size(10).OrderByTermDesc()
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"field":"gender","order":[{"_term":"desc"}],"size":10}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithSubAggregation(t *testing.T) {
- subAgg := NewAvgAggregation().Field("height")
- agg := NewTermsAggregation().Field("gender").Size(10).
- OrderByAggregation("avg_height", false)
- agg = agg.SubAggregation("avg_height", subAgg)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_height":{"avg":{"field":"height"}}},"terms":{"field":"gender","order":[{"avg_height":"desc"}],"size":10}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithMultipleSubAggregation(t *testing.T) {
- subAgg1 := NewAvgAggregation().Field("height")
- subAgg2 := NewAvgAggregation().Field("width")
- agg := NewTermsAggregation().Field("gender").Size(10).
- OrderByAggregation("avg_height", false)
- agg = agg.SubAggregation("avg_height", subAgg1)
- agg = agg.SubAggregation("avg_width", subAgg2)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_height":{"avg":{"field":"height"}},"avg_width":{"avg":{"field":"width"}}},"terms":{"field":"gender","order":[{"avg_height":"desc"}],"size":10}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithMetaData(t *testing.T) {
- agg := NewTermsAggregation().Field("gender").Size(10).OrderByTermDesc()
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"terms":{"field":"gender","order":[{"_term":"desc"}],"size":10}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithMissing(t *testing.T) {
- agg := NewTermsAggregation().Field("gender").Size(10).Missing("n/a")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"field":"gender","missing":"n/a","size":10}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithIncludeExclude(t *testing.T) {
- agg := NewTermsAggregation().Field("tags").Include(".*sport.*").Exclude("water_.*")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"exclude":"water_.*","field":"tags","include":".*sport.*"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithIncludeExcludeValues(t *testing.T) {
- agg := NewTermsAggregation().Field("make").IncludeValues("mazda", "honda").ExcludeValues("rover", "jensen")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"exclude":["rover","jensen"],"field":"make","include":["mazda","honda"]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsAggregationWithPartitions(t *testing.T) {
- agg := NewTermsAggregation().Field("account_id").Partition(0).NumPartitions(20)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"field":"account_id","include":{"num_partitions":20,"partition":0}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats.go
index 785f392b6..875da0718 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats.go
@@ -5,7 +5,7 @@
package elastic
// MatrixMatrixStatsAggregation ...
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-stats-aggregation.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-aggregations-metrics-stats-aggregation.html
// for details.
type MatrixStatsAggregation struct {
fields []string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats_test.go
deleted file mode 100644
index 28138fe02..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_matrix_stats_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatrixStatsAggregation(t *testing.T) {
- agg := NewMatrixStatsAggregation().
- Fields("poverty", "income").
- Missing(map[string]interface{}{
- "income": 50000,
- }).
- Mode("avg").
- Format("0000.0").
- ValueType("double")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"matrix_stats":{"fields":["poverty","income"],"format":"0000.0","missing":{"income":50000},"mode":"avg","value_type":"double"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMatrixStatsAggregationWithMetaData(t *testing.T) {
- agg := NewMatrixStatsAggregation().
- Fields("poverty", "income").
- Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"matrix_stats":{"fields":["poverty","income"]},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg.go
index 2b764e065..ff337a8cd 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg.go
@@ -9,7 +9,7 @@ package elastic
// aggregated documents. These values can be extracted either from
// specific numeric fields in the documents, or be generated by
// a provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-avg-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-avg-aggregation.html
type AvgAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg_test.go
deleted file mode 100644
index 784ff45dd..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_avg_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestAvgAggregation(t *testing.T) {
- agg := NewAvgAggregation().Field("grade")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"avg":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestAvgAggregationWithFormat(t *testing.T) {
- agg := NewAvgAggregation().Field("grade").Format("000.0")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"avg":{"field":"grade","format":"000.0"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestAvgAggregationWithMetaData(t *testing.T) {
- agg := NewAvgAggregation().Field("grade").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"avg":{"field":"grade"},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality.go
index 3b999c849..8f6f447c4 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality.go
@@ -8,7 +8,7 @@ package elastic
// calculates an approximate count of distinct values.
// Values can be extracted either from specific fields in the document
// or generated by a script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-cardinality-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-cardinality-aggregation.html
type CardinalityAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality_test.go
deleted file mode 100644
index b5f8490b5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_cardinality_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestCardinalityAggregation(t *testing.T) {
- agg := NewCardinalityAggregation().Field("author.hash")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"cardinality":{"field":"author.hash"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCardinalityAggregationWithOptions(t *testing.T) {
- agg := NewCardinalityAggregation().Field("author.hash").PrecisionThreshold(100).Rehash(true)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"cardinality":{"field":"author.hash","precision_threshold":100,"rehash":true}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCardinalityAggregationWithFormat(t *testing.T) {
- agg := NewCardinalityAggregation().Field("author.hash").Format("00000")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"cardinality":{"field":"author.hash","format":"00000"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCardinalityAggregationWithMetaData(t *testing.T) {
- agg := NewCardinalityAggregation().Field("author.hash").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"cardinality":{"field":"author.hash"},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats.go
index 4e0bbe65a..95b312686 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats.go
@@ -8,7 +8,7 @@ package elastic
// computes stats over numeric values extracted from the aggregated documents.
// These values can be extracted either from specific numeric fields
// in the documents, or be generated by a provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-extendedstats-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-extendedstats-aggregation.html
type ExtendedStatsAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats_test.go
deleted file mode 100644
index 76489630d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_extended_stats_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestExtendedStatsAggregation(t *testing.T) {
- agg := NewExtendedStatsAggregation().Field("grade")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"extended_stats":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestExtendedStatsAggregationWithFormat(t *testing.T) {
- agg := NewExtendedStatsAggregation().Field("grade").Format("000.0")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"extended_stats":{"field":"grade","format":"000.0"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds.go
index 406f2d000..c263a76b4 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds.go
@@ -6,7 +6,7 @@ package elastic
// GeoBoundsAggregation is a metric aggregation that computes the
// bounding box containing all geo_point values for a field.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-geobounds-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-geobounds-aggregation.html
type GeoBoundsAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds_test.go
deleted file mode 100644
index ea713c604..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_bounds_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoBoundsAggregation(t *testing.T) {
- agg := NewGeoBoundsAggregation().Field("location")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_bounds":{"field":"location"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoBoundsAggregationWithWrapLongitude(t *testing.T) {
- agg := NewGeoBoundsAggregation().Field("location").WrapLongitude(true)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_bounds":{"field":"location","wrap_longitude":true}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoBoundsAggregationWithMetaData(t *testing.T) {
- agg := NewGeoBoundsAggregation().Field("location").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_bounds":{"field":"location"},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_centroid.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_centroid.go
new file mode 100644
index 000000000..a3470794a
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_geo_centroid.go
@@ -0,0 +1,95 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+// GeoCentroidAggregation is a metric aggregation that computes the weighted centroid
+// from all coordinate values for a Geo-point datatype field.
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-metrics-geocentroid-aggregation.html
+type GeoCentroidAggregation struct {
+ field string
+ script *Script
+ subAggregations map[string]Aggregation
+ meta map[string]interface{}
+}
+
+func NewGeoCentroidAggregation() *GeoCentroidAggregation {
+ return &GeoCentroidAggregation{
+ subAggregations: make(map[string]Aggregation),
+ }
+}
+
+func (a *GeoCentroidAggregation) Field(field string) *GeoCentroidAggregation {
+ a.field = field
+ return a
+}
+
+func (a *GeoCentroidAggregation) Script(script *Script) *GeoCentroidAggregation {
+ a.script = script
+ return a
+}
+
+func (a *GeoCentroidAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoCentroidAggregation {
+ a.subAggregations[name] = subAggregation
+ return a
+}
+
+// Meta sets the meta data to be included in the aggregation response.
+func (a *GeoCentroidAggregation) Meta(metaData map[string]interface{}) *GeoCentroidAggregation {
+ a.meta = metaData
+ return a
+}
+
+func (a *GeoCentroidAggregation) Source() (interface{}, error) {
+ // Example:
+ // {
+ // "query" : {
+ // "match" : { "business_type" : "shop" }
+ // },
+ // "aggs" : {
+ // "centroid" : {
+ // "geo_centroid" : {
+ // "field" : "location"
+ // }
+ // }
+ // }
+ // }
+ //
+ // This method returns only the { "geo_centroid" : { ... } } part.
+
+ source := make(map[string]interface{})
+ opts := make(map[string]interface{})
+ source["geo_centroid"] = opts
+
+ if a.field != "" {
+ opts["field"] = a.field
+ }
+ if a.script != nil {
+ src, err := a.script.Source()
+ if err != nil {
+ return nil, err
+ }
+ opts["script"] = src
+ }
+
+ // AggregationBuilder (SubAggregations)
+ if len(a.subAggregations) > 0 {
+ aggsMap := make(map[string]interface{})
+ source["aggregations"] = aggsMap
+ for name, aggregate := range a.subAggregations {
+ src, err := aggregate.Source()
+ if err != nil {
+ return nil, err
+ }
+ aggsMap[name] = src
+ }
+ }
+
+ // Add Meta data if available
+ if len(a.meta) > 0 {
+ source["meta"] = a.meta
+ }
+
+ return source, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max.go
index acdfa14a8..b62130676 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max.go
@@ -9,7 +9,7 @@ package elastic
// the aggregated documents. These values can be extracted either from
// specific numeric fields in the documents, or be generated by
// a provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-max-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-max-aggregation.html
type MaxAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max_test.go
deleted file mode 100644
index 773cc2e4b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_max_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMaxAggregation(t *testing.T) {
- agg := NewMaxAggregation().Field("price")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"max":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMaxAggregationWithFormat(t *testing.T) {
- agg := NewMaxAggregation().Field("price").Format("00000.00")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"max":{"field":"price","format":"00000.00"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMaxAggregationWithMetaData(t *testing.T) {
- agg := NewMaxAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"max":{"field":"price"},"meta":{"name":"Oliver"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min.go
index af63585da..c1ca6922b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min.go
@@ -9,7 +9,7 @@ package elastic
// aggregated documents. These values can be extracted either from
// specific numeric fields in the documents, or be generated by a
// provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-min-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-min-aggregation.html
type MinAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min_test.go
deleted file mode 100644
index fcde3817c..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_min_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMinAggregation(t *testing.T) {
- agg := NewMinAggregation().Field("price")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"min":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMinAggregationWithFormat(t *testing.T) {
- agg := NewMinAggregation().Field("price").Format("00000.00")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"min":{"field":"price","format":"00000.00"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMinAggregationWithMetaData(t *testing.T) {
- agg := NewMinAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"min":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks.go
index 674fc41f9..3e0595e88 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks.go
@@ -5,7 +5,7 @@
package elastic
// PercentileRanksAggregation
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-percentile-rank-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-rank-aggregation.html
type PercentileRanksAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks_test.go
deleted file mode 100644
index a4bac02b5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentile_ranks_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPercentileRanksAggregation(t *testing.T) {
- agg := NewPercentileRanksAggregation().Field("load_time")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentile_ranks":{"field":"load_time"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentileRanksAggregationWithCustomValues(t *testing.T) {
- agg := NewPercentileRanksAggregation().Field("load_time").Values(15, 30)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentile_ranks":{"field":"load_time","values":[15,30]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentileRanksAggregationWithFormat(t *testing.T) {
- agg := NewPercentileRanksAggregation().Field("load_time").Format("000.0")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentile_ranks":{"field":"load_time","format":"000.0"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentileRanksAggregationWithMetaData(t *testing.T) {
- agg := NewPercentileRanksAggregation().Field("load_time").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"percentile_ranks":{"field":"load_time"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles.go
index a1d78c8f2..411f9c50f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles.go
@@ -5,7 +5,7 @@
package elastic
// PercentilesAggregation
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-percentile-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-aggregation.html
type PercentilesAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles_test.go
deleted file mode 100644
index 93df1dd29..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_percentiles_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPercentilesAggregation(t *testing.T) {
- agg := NewPercentilesAggregation().Field("price")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentiles":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentilesAggregationWithCustomPercents(t *testing.T) {
- agg := NewPercentilesAggregation().Field("price").Percentiles(0.2, 0.5, 0.9)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentiles":{"field":"price","percents":[0.2,0.5,0.9]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentilesAggregationWithFormat(t *testing.T) {
- agg := NewPercentilesAggregation().Field("price").Format("00000.00")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentiles":{"field":"price","format":"00000.00"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentilesAggregationWithMetaData(t *testing.T) {
- agg := NewPercentilesAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"percentiles":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats.go
index b9bbe7cff..400b79b00 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats.go
@@ -8,7 +8,7 @@ package elastic
// over numeric values extracted from the aggregated documents.
// These values can be extracted either from specific numeric fields
// in the documents, or be generated by a provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-stats-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-stats-aggregation.html
type StatsAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats_test.go
deleted file mode 100644
index 5cff372d4..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_stats_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestStatsAggregation(t *testing.T) {
- agg := NewStatsAggregation().Field("grade")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"stats":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestStatsAggregationWithFormat(t *testing.T) {
- agg := NewStatsAggregation().Field("grade").Format("0000.0")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"stats":{"field":"grade","format":"0000.0"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestStatsAggregationWithMetaData(t *testing.T) {
- agg := NewStatsAggregation().Field("grade").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"stats":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum.go
index e1c07c9c1..f959a3e54 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum.go
@@ -8,7 +8,7 @@ package elastic
// numeric values that are extracted from the aggregated documents.
// These values can be extracted either from specific numeric fields
// in the documents, or be generated by a provided script.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-sum-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-sum-aggregation.html
type SumAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum_test.go
deleted file mode 100644
index ff0e42545..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_sum_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSumAggregation(t *testing.T) {
- agg := NewSumAggregation().Field("price")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"sum":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSumAggregationWithFormat(t *testing.T) {
- agg := NewSumAggregation().Field("price").Format("00000.00")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"sum":{"field":"price","format":"00000.00"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSumAggregationWithMetaData(t *testing.T) {
- agg := NewSumAggregation().Field("price").Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"sum":{"field":"price"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits.go
index 2b181895e..43dd36cdb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits.go
@@ -13,7 +13,7 @@ package elastic
// a bucket aggregator. One or more bucket aggregators determines by
// which properties a result set get sliced into.
//
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-top-hits-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-top-hits-aggregation.html
type TopHitsAggregation struct {
searchSource *SearchSource
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits_test.go
deleted file mode 100644
index 861f079fe..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_top_hits_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTopHitsAggregation(t *testing.T) {
- fsc := NewFetchSourceContext(true).Include("title")
- agg := NewTopHitsAggregation().
- Sort("last_activity_date", false).
- FetchSourceContext(fsc).
- Size(1)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"top_hits":{"_source":{"includes":["title"]},"size":1,"sort":[{"last_activity_date":{"order":"desc"}}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count.go
index d56f1f873..4e7281d62 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count.go
@@ -11,7 +11,7 @@ package elastic
// used in conjunction with other single-value aggregations.
// For example, when computing the avg one might be interested in the
// number of values the average is computed over.
-// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-valuecount-aggregation.html
+// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-valuecount-aggregation.html
type ValueCountAggregation struct {
field string
script *Script
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count_test.go
deleted file mode 100644
index 18d2ba119..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_metrics_value_count_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestValueCountAggregation(t *testing.T) {
- agg := NewValueCountAggregation().Field("grade")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"value_count":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestValueCountAggregationWithFormat(t *testing.T) {
- // Format comes with 1.5.0+
- agg := NewValueCountAggregation().Field("grade").Format("0000.0")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"value_count":{"field":"grade","format":"0000.0"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestValueCountAggregationWithMetaData(t *testing.T) {
- agg := NewValueCountAggregation().Field("grade")
- agg = agg.Meta(map[string]interface{}{"name": "Oliver"})
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"meta":{"name":"Oliver"},"value_count":{"field":"grade"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket.go
index f37a9bdb8..7eea9310d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket.go
@@ -10,7 +10,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-avg-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-avg-bucket-aggregation.html
type AvgBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket_test.go
deleted file mode 100644
index 019b8f1ad..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_avg_bucket_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestAvgBucketAggregation(t *testing.T) {
- agg := NewAvgBucketAggregation().BucketsPath("the_sum").GapPolicy("skip")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"avg_bucket":{"buckets_path":"the_sum","gap_policy":"skip"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script.go
index 34e356964..13cad638f 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script.go
@@ -10,7 +10,7 @@ package elastic
// numeric and the script must return a numeric value.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-bucket-script-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-script-aggregation.html
type BucketScriptAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script_test.go
deleted file mode 100644
index 3c101c706..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_script_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestBucketScriptAggregation(t *testing.T) {
- agg := NewBucketScriptAggregation().
- AddBucketsPath("tShirtSales", "t-shirts>sales").
- AddBucketsPath("totalSales", "total_sales").
- Script(NewScript("tShirtSales / totalSales * 100"))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"bucket_script":{"buckets_path":{"tShirtSales":"t-shirts\u003esales","totalSales":"total_sales"},"script":{"source":"tShirtSales / totalSales * 100"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector.go
index 233414d70..f3c938519 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector.go
@@ -12,7 +12,7 @@ package elastic
// will be evaluated as false and all other values will evaluate to true.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-bucket-selector-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-selector-aggregation.html
type BucketSelectorAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector_test.go
deleted file mode 100644
index e378c2832..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_bucket_selector_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestBucketSelectorAggregation(t *testing.T) {
- agg := NewBucketSelectorAggregation().
- AddBucketsPath("totalSales", "total_sales").
- Script(NewScript("totalSales >= 1000"))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"bucket_selector":{"buckets_path":{"totalSales":"total_sales"},"script":{"source":"totalSales \u003e= 1000"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum.go
index 80a1db42d..95546f1cb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum.go
@@ -10,7 +10,7 @@ package elastic
// histogram must have min_doc_count set to 0 (default for histogram aggregations).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-cumulative-sum-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-cumulative-sum-aggregation.html
type CumulativeSumAggregation struct {
format string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum_test.go
deleted file mode 100644
index 69a215d43..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_cumulative_sum_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestCumulativeSumAggregation(t *testing.T) {
- agg := NewCumulativeSumAggregation().BucketsPath("sales")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"cumulative_sum":{"buckets_path":"sales"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative.go
index ee7114e25..2c3c7e03a 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative.go
@@ -10,7 +10,7 @@ package elastic
// histogram must have min_doc_count set to 0 (default for histogram aggregations).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-derivative-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-derivative-aggregation.html
type DerivativeAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative_test.go
deleted file mode 100644
index 7e7b26749..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_derivative_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestDerivativeAggregation(t *testing.T) {
- agg := NewDerivativeAggregation().BucketsPath("sales")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"derivative":{"buckets_path":"sales"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket.go
index 5da049561..5a10b0e45 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket.go
@@ -11,7 +11,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-max-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-max-bucket-aggregation.html
type MaxBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket_test.go
deleted file mode 100644
index aa9bf2f6d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_max_bucket_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMaxBucketAggregation(t *testing.T) {
- agg := NewMaxBucketAggregation().BucketsPath("the_sum").GapPolicy("skip")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"max_bucket":{"buckets_path":"the_sum","gap_policy":"skip"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket.go
index 463bb919e..96982250c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket.go
@@ -11,7 +11,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-min-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-min-bucket-aggregation.html
type MinBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket_test.go
deleted file mode 100644
index ff4abf2b2..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_min_bucket_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMinBucketAggregation(t *testing.T) {
- agg := NewMinBucketAggregation().BucketsPath("sales_per_month>sales").GapPolicy("skip")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"min_bucket":{"buckets_path":"sales_per_month\u003esales","gap_policy":"skip"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg.go
index 821d73842..cf94342f7 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg.go
@@ -8,7 +8,7 @@ package elastic
// across the data and emit the average value of that window.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html
type MovAvgAggregation struct {
format string
gapPolicy string
@@ -162,7 +162,7 @@ func (a *MovAvgAggregation) Source() (interface{}, error) {
}
// -- Models for moving averages --
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_models
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_models
// MovAvgModel specifies the model to use with the MovAvgAggregation.
type MovAvgModel interface {
@@ -175,7 +175,7 @@ type MovAvgModel interface {
// EWMAMovAvgModel calculates an exponentially weighted moving average.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_ewma_exponentially_weighted
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_ewma_exponentially_weighted
type EWMAMovAvgModel struct {
alpha *float64
}
@@ -213,7 +213,7 @@ func (m *EWMAMovAvgModel) Settings() map[string]interface{} {
// HoltLinearMovAvgModel calculates a doubly exponential weighted moving average.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_holt_linear
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_holt_linear
type HoltLinearMovAvgModel struct {
alpha *float64
beta *float64
@@ -262,7 +262,7 @@ func (m *HoltLinearMovAvgModel) Settings() map[string]interface{} {
// HoltWintersMovAvgModel calculates a triple exponential weighted moving average.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_holt_winters
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_holt_winters
type HoltWintersMovAvgModel struct {
alpha *float64
beta *float64
@@ -349,7 +349,7 @@ func (m *HoltWintersMovAvgModel) Settings() map[string]interface{} {
// by position in collection.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_linear
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_linear
type LinearMovAvgModel struct {
}
@@ -373,7 +373,7 @@ func (m *LinearMovAvgModel) Settings() map[string]interface{} {
// SimpleMovAvgModel calculates a simple unweighted (arithmetic) moving average.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-movavg-aggregation.html#_simple
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html#_simple
type SimpleMovAvgModel struct {
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg_test.go
deleted file mode 100644
index af2fc7c27..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_mov_avg_test.go
+++ /dev/null
@@ -1,132 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMovAvgAggregation(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithSimpleModel(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum").Window(30).Model(NewSimpleMovAvgModel())
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum","model":"simple","window":30}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithLinearModel(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum").Window(30).Model(NewLinearMovAvgModel())
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum","model":"linear","window":30}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithEWMAModel(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum").Window(30).Model(NewEWMAMovAvgModel().Alpha(0.5))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum","model":"ewma","settings":{"alpha":0.5},"window":30}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithHoltLinearModel(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum").Window(30).
- Model(NewHoltLinearMovAvgModel().Alpha(0.5).Beta(0.4))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum","model":"holt","settings":{"alpha":0.5,"beta":0.4},"window":30}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithHoltWintersModel(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum").Window(30).Predict(10).Minimize(true).
- Model(NewHoltWintersMovAvgModel().Alpha(0.5).Beta(0.4).Gamma(0.3).Period(7).Pad(true))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"moving_avg":{"buckets_path":"the_sum","minimize":true,"model":"holt_winters","predict":10,"settings":{"alpha":0.5,"beta":0.4,"gamma":0.3,"pad":true,"period":7},"window":30}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMovAvgAggregationWithSubAggs(t *testing.T) {
- agg := NewMovAvgAggregation().BucketsPath("the_sum")
- agg = agg.SubAggregation("avg_sum", NewAvgAggregation().Field("height"))
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"aggregations":{"avg_sum":{"avg":{"field":"height"}}},"moving_avg":{"buckets_path":"the_sum"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket.go
index 9a3556269..4caca7432 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket.go
@@ -10,7 +10,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-percentiles-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-percentiles-bucket-aggregation.html
type PercentilesBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket_test.go
deleted file mode 100644
index 5fa2639de..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_percentiles_bucket_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPercentilesBucketAggregation(t *testing.T) {
- agg := NewPercentilesBucketAggregation().BucketsPath("the_sum").GapPolicy("skip")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentiles_bucket":{"buckets_path":"the_sum","gap_policy":"skip"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercentilesBucketAggregationWithPercents(t *testing.T) {
- agg := NewPercentilesBucketAggregation().BucketsPath("the_sum").Percents(0.1, 1.0, 5.0, 25, 50)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percentiles_bucket":{"buckets_path":"the_sum","percents":[0.1,1,5,25,50]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff.go
index e13b94ea9..84ae43004 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff.go
@@ -9,7 +9,7 @@ package elastic
// subtracted from itself at different time lags or periods.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-serialdiff-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-serialdiff-aggregation.html
type SerialDiffAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff_test.go
deleted file mode 100644
index 6d336a2ee..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_serial_diff_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSerialDiffAggregation(t *testing.T) {
- agg := NewSerialDiffAggregation().BucketsPath("the_sum").Lag(7)
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"serial_diff":{"buckets_path":"the_sum","lag":7}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket.go
index e68a420f2..fb0a94afc 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket.go
@@ -10,7 +10,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-stats-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-stats-bucket-aggregation.html
type StatsBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket_test.go
deleted file mode 100644
index 117a73885..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_stats_bucket_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestStatsBucketAggregation(t *testing.T) {
- agg := NewStatsBucketAggregation().BucketsPath("the_sum").GapPolicy("skip")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"stats_bucket":{"buckets_path":"the_sum","gap_policy":"skip"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket.go
index c22ae8f50..1f78efa56 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket.go
@@ -10,7 +10,7 @@ package elastic
// be a multi-bucket aggregation.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-pipeline-sum-bucket-aggregation.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-sum-bucket-aggregation.html
type SumBucketAggregation struct {
format string
gapPolicy string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket_test.go
deleted file mode 100644
index be8275c81..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_sum_bucket_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSumBucketAggregation(t *testing.T) {
- agg := NewSumBucketAggregation().BucketsPath("the_sum")
- src, err := agg.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"sum_bucket":{"buckets_path":"the_sum"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_test.go
deleted file mode 100644
index 24dd4eb0f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_pipeline_test.go
+++ /dev/null
@@ -1,903 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestAggsIntegrationAvgBucket(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- builder = builder.Aggregation("sales_per_month", h)
- builder = builder.Aggregation("avg_monthly_sales", NewAvgBucketAggregation().BucketsPath("sales_per_month>sales"))
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.AvgBucket("avg_monthly_sales")
- if !found {
- t.Fatal("expected avg_monthly_sales aggregation")
- }
- if agg == nil {
- t.Fatal("expected avg_monthly_sales aggregation")
- }
- if agg.Value == nil {
- t.Fatal("expected avg_monthly_sales.value != nil")
- }
- if got, want := *agg.Value, float64(939.2); got != want {
- t.Fatalf("expected avg_monthly_sales.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationDerivative(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- h = h.SubAggregation("sales_deriv", NewDerivativeAggregation().BucketsPath("sales"))
- builder = builder.Aggregation("sales_per_month", h)
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("sales_per_month")
- if !found {
- t.Fatal("expected sales_per_month aggregation")
- }
- if agg == nil {
- t.Fatal("expected sales_per_month aggregation")
- }
- if got, want := len(agg.Buckets), 6; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- if got, want := agg.Buckets[0].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[1].DocCount, int64(0); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[2].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[3].DocCount, int64(3); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[4].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[5].DocCount, int64(2); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
-
- d, found := agg.Buckets[0].Derivative("sales_deriv")
- if found {
- t.Fatal("expected no sales_deriv aggregation")
- }
- if d != nil {
- t.Fatal("expected no sales_deriv aggregation")
- }
-
- d, found = agg.Buckets[1].Derivative("sales_deriv")
- if !found {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d == nil {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d.Value != nil {
- t.Fatal("expected sales_deriv value == nil")
- }
-
- d, found = agg.Buckets[2].Derivative("sales_deriv")
- if !found {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d == nil {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d.Value != nil {
- t.Fatal("expected sales_deriv value == nil")
- }
-
- d, found = agg.Buckets[3].Derivative("sales_deriv")
- if !found {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d == nil {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected sales_deriv value != nil")
- }
- if got, want := *d.Value, float64(2348.0); got != want {
- t.Fatalf("expected sales_deriv.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[4].Derivative("sales_deriv")
- if !found {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d == nil {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected sales_deriv value != nil")
- }
- if got, want := *d.Value, float64(-1658.0); got != want {
- t.Fatalf("expected sales_deriv.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[5].Derivative("sales_deriv")
- if !found {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d == nil {
- t.Fatal("expected sales_deriv aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected sales_deriv value != nil")
- }
- if got, want := *d.Value, float64(-722.0); got != want {
- t.Fatalf("expected sales_deriv.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationMaxBucket(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- builder = builder.Aggregation("sales_per_month", h)
- builder = builder.Aggregation("max_monthly_sales", NewMaxBucketAggregation().BucketsPath("sales_per_month>sales"))
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.MaxBucket("max_monthly_sales")
- if !found {
- t.Fatal("expected max_monthly_sales aggregation")
- }
- if agg == nil {
- t.Fatal("expected max_monthly_sales aggregation")
- }
- if got, want := len(agg.Keys), 1; got != want {
- t.Fatalf("expected len(max_monthly_sales.keys)=%d; got: %d", want, got)
- }
- if got, want := agg.Keys[0], "2015-04-01"; got != want {
- t.Fatalf("expected max_monthly_sales.keys[0]=%v; got: %v", want, got)
- }
- if agg.Value == nil {
- t.Fatal("expected max_monthly_sales.value != nil")
- }
- if got, want := *agg.Value, float64(2448); got != want {
- t.Fatalf("expected max_monthly_sales.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationMinBucket(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- builder = builder.Aggregation("sales_per_month", h)
- builder = builder.Aggregation("min_monthly_sales", NewMinBucketAggregation().BucketsPath("sales_per_month>sales"))
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.MinBucket("min_monthly_sales")
- if !found {
- t.Fatal("expected min_monthly_sales aggregation")
- }
- if agg == nil {
- t.Fatal("expected min_monthly_sales aggregation")
- }
- if got, want := len(agg.Keys), 1; got != want {
- t.Fatalf("expected len(min_monthly_sales.keys)=%d; got: %d", want, got)
- }
- if got, want := agg.Keys[0], "2015-06-01"; got != want {
- t.Fatalf("expected min_monthly_sales.keys[0]=%v; got: %v", want, got)
- }
- if agg.Value == nil {
- t.Fatal("expected min_monthly_sales.value != nil")
- }
- if got, want := *agg.Value, float64(68); got != want {
- t.Fatalf("expected min_monthly_sales.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationSumBucket(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- builder = builder.Aggregation("sales_per_month", h)
- builder = builder.Aggregation("sum_monthly_sales", NewSumBucketAggregation().BucketsPath("sales_per_month>sales"))
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.SumBucket("sum_monthly_sales")
- if !found {
- t.Fatal("expected sum_monthly_sales aggregation")
- }
- if agg == nil {
- t.Fatal("expected sum_monthly_sales aggregation")
- }
- if agg.Value == nil {
- t.Fatal("expected sum_monthly_sales.value != nil")
- }
- if got, want := *agg.Value, float64(4696.0); got != want {
- t.Fatalf("expected sum_monthly_sales.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationMovAvg(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("the_sum", NewSumAggregation().Field("price"))
- h = h.SubAggregation("the_movavg", NewMovAvgAggregation().BucketsPath("the_sum"))
- builder = builder.Aggregation("my_date_histo", h)
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("my_date_histo")
- if !found {
- t.Fatal("expected sum_monthly_sales aggregation")
- }
- if agg == nil {
- t.Fatal("expected sum_monthly_sales aggregation")
- }
- if got, want := len(agg.Buckets), 6; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- d, found := agg.Buckets[0].MovAvg("the_movavg")
- if found {
- t.Fatal("expected no the_movavg aggregation")
- }
- if d != nil {
- t.Fatal("expected no the_movavg aggregation")
- }
-
- d, found = agg.Buckets[1].MovAvg("the_movavg")
- if found {
- t.Fatal("expected no the_movavg aggregation")
- }
- if d != nil {
- t.Fatal("expected no the_movavg aggregation")
- }
-
- d, found = agg.Buckets[2].MovAvg("the_movavg")
- if !found {
- t.Fatal("expected the_movavg aggregation")
- }
- if d == nil {
- t.Fatal("expected the_movavg aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_movavg value")
- }
- if got, want := *d.Value, float64(1290.0); got != want {
- t.Fatalf("expected %v buckets; got: %v", want, got)
- }
-
- d, found = agg.Buckets[3].MovAvg("the_movavg")
- if !found {
- t.Fatal("expected the_movavg aggregation")
- }
- if d == nil {
- t.Fatal("expected the_movavg aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_movavg value")
- }
- if got, want := *d.Value, float64(695.0); got != want {
- t.Fatalf("expected %v buckets; got: %v", want, got)
- }
-
- d, found = agg.Buckets[4].MovAvg("the_movavg")
- if !found {
- t.Fatal("expected the_movavg aggregation")
- }
- if d == nil {
- t.Fatal("expected the_movavg aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_movavg value")
- }
- if got, want := *d.Value, float64(1279.3333333333333); got != want {
- t.Fatalf("expected %v buckets; got: %v", want, got)
- }
-
- d, found = agg.Buckets[5].MovAvg("the_movavg")
- if !found {
- t.Fatal("expected the_movavg aggregation")
- }
- if d == nil {
- t.Fatal("expected the_movavg aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_movavg value")
- }
- if got, want := *d.Value, float64(1157.0); got != want {
- t.Fatalf("expected %v buckets; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationCumulativeSum(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- h = h.SubAggregation("cumulative_sales", NewCumulativeSumAggregation().BucketsPath("sales"))
- builder = builder.Aggregation("sales_per_month", h)
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("sales_per_month")
- if !found {
- t.Fatal("expected sales_per_month aggregation")
- }
- if agg == nil {
- t.Fatal("expected sales_per_month aggregation")
- }
- if got, want := len(agg.Buckets), 6; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- if got, want := agg.Buckets[0].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[1].DocCount, int64(0); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[2].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[3].DocCount, int64(3); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[4].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[5].DocCount, int64(2); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
-
- d, found := agg.Buckets[0].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(1290.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[1].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(1290.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[2].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(1390.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[3].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(3838.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[4].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(4628.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[5].CumulativeSum("cumulative_sales")
- if !found {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d == nil {
- t.Fatal("expected cumulative_sales aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected cumulative_sales value != nil")
- }
- if got, want := *d.Value, float64(4696.0); got != want {
- t.Fatalf("expected cumulative_sales.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationBucketScript(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("total_sales", NewSumAggregation().Field("price"))
- appleFilter := NewFilterAggregation().Filter(NewTermQuery("manufacturer", "Apple"))
- appleFilter = appleFilter.SubAggregation("sales", NewSumAggregation().Field("price"))
- h = h.SubAggregation("apple_sales", appleFilter)
- h = h.SubAggregation("apple_percentage",
- NewBucketScriptAggregation().
- GapPolicy("insert_zeros").
- AddBucketsPath("appleSales", "apple_sales>sales").
- AddBucketsPath("totalSales", "total_sales").
- Script(NewScript("params.appleSales / params.totalSales * 100")))
- builder = builder.Aggregation("sales_per_month", h)
-
- res, err := builder.Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatalf("%v (maybe scripting is disabled?)", err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("sales_per_month")
- if !found {
- t.Fatal("expected sales_per_month aggregation")
- }
- if agg == nil {
- t.Fatal("expected sales_per_month aggregation")
- }
- if got, want := len(agg.Buckets), 6; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- if got, want := agg.Buckets[0].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[1].DocCount, int64(0); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[2].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[3].DocCount, int64(3); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[4].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[5].DocCount, int64(2); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
-
- d, found := agg.Buckets[0].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected apple_percentage value != nil")
- }
- if got, want := *d.Value, float64(100.0); got != want {
- t.Fatalf("expected apple_percentage.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[1].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value != nil {
- t.Fatal("expected apple_percentage value == nil")
- }
-
- d, found = agg.Buckets[2].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected apple_percentage value != nil")
- }
- if got, want := *d.Value, float64(0.0); got != want {
- t.Fatalf("expected apple_percentage.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[3].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected apple_percentage value != nil")
- }
- if got, want := *d.Value, float64(34.64052287581699); got != want {
- t.Fatalf("expected apple_percentage.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[4].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected apple_percentage value != nil")
- }
- if got, want := *d.Value, float64(0.0); got != want {
- t.Fatalf("expected apple_percentage.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[5].BucketScript("apple_percentage")
- if !found {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d == nil {
- t.Fatal("expected apple_percentage aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected apple_percentage value != nil")
- }
- if got, want := *d.Value, float64(0.0); got != want {
- t.Fatalf("expected apple_percentage.value=%v; got: %v", want, got)
- }
-}
-
-func TestAggsIntegrationBucketSelector(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("total_sales", NewSumAggregation().Field("price"))
- h = h.SubAggregation("sales_bucket_filter",
- NewBucketSelectorAggregation().
- AddBucketsPath("totalSales", "total_sales").
- Script(NewScript("params.totalSales <= 100")))
- builder = builder.Aggregation("sales_per_month", h)
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatalf("%v (maybe scripting is disabled?)", err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("sales_per_month")
- if !found {
- t.Fatal("expected sales_per_month aggregation")
- }
- if agg == nil {
- t.Fatal("expected sales_per_month aggregation")
- }
- if got, want := len(agg.Buckets), 2; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- if got, want := agg.Buckets[0].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[1].DocCount, int64(2); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
-}
-
-func TestAggsIntegrationSerialDiff(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- builder := client.Search().
- Index(testOrderIndex).
- Type("doc").
- Query(NewMatchAllQuery()).
- Pretty(true)
- h := NewDateHistogramAggregation().Field("time").Interval("month")
- h = h.SubAggregation("sales", NewSumAggregation().Field("price"))
- h = h.SubAggregation("the_diff", NewSerialDiffAggregation().BucketsPath("sales").Lag(1))
- builder = builder.Aggregation("sales_per_month", h)
-
- res, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
-
- aggs := res.Aggregations
- if aggs == nil {
- t.Fatal("expected aggregations != nil; got: nil")
- }
-
- agg, found := aggs.DateHistogram("sales_per_month")
- if !found {
- t.Fatal("expected sales_per_month aggregation")
- }
- if agg == nil {
- t.Fatal("expected sales_per_month aggregation")
- }
- if got, want := len(agg.Buckets), 6; got != want {
- t.Fatalf("expected %d buckets; got: %d", want, got)
- }
-
- if got, want := agg.Buckets[0].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[1].DocCount, int64(0); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[2].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[3].DocCount, int64(3); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[4].DocCount, int64(1); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
- if got, want := agg.Buckets[5].DocCount, int64(2); got != want {
- t.Fatalf("expected DocCount=%d; got: %d", want, got)
- }
-
- d, found := agg.Buckets[0].SerialDiff("the_diff")
- if found {
- t.Fatal("expected no the_diff aggregation")
- }
- if d != nil {
- t.Fatal("expected no the_diff aggregation")
- }
-
- d, found = agg.Buckets[1].SerialDiff("the_diff")
- if found {
- t.Fatal("expected no the_diff aggregation")
- }
- if d != nil {
- t.Fatal("expected no the_diff aggregation")
- }
-
- d, found = agg.Buckets[2].SerialDiff("the_diff")
- if found {
- t.Fatal("expected no the_diff aggregation")
- }
- if d != nil {
- t.Fatal("expected no the_diff aggregation")
- }
-
- d, found = agg.Buckets[3].SerialDiff("the_diff")
- if !found {
- t.Fatal("expected the_diff aggregation")
- }
- if d == nil {
- t.Fatal("expected the_diff aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_diff value != nil")
- }
- if got, want := *d.Value, float64(2348.0); got != want {
- t.Fatalf("expected the_diff.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[4].SerialDiff("the_diff")
- if !found {
- t.Fatal("expected the_diff aggregation")
- }
- if d == nil {
- t.Fatal("expected the_diff aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_diff value != nil")
- }
- if got, want := *d.Value, float64(-1658.0); got != want {
- t.Fatalf("expected the_diff.value=%v; got: %v", want, got)
- }
-
- d, found = agg.Buckets[5].SerialDiff("the_diff")
- if !found {
- t.Fatal("expected the_diff aggregation")
- }
- if d == nil {
- t.Fatal("expected the_diff aggregation")
- }
- if d.Value == nil {
- t.Fatal("expected the_diff value != nil")
- }
- if got, want := *d.Value, float64(-722.0); got != want {
- t.Fatalf("expected the_diff.value=%v; got: %v", want, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_aggs_test.go
deleted file mode 100644
index f1b6347b3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_aggs_test.go
+++ /dev/null
@@ -1,3416 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "strings"
- "testing"
- "time"
-)
-
-func TestAggs(t *testing.T) {
- //client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndex(t)
-
- /*
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- */
-
- tweet1 := tweet{
- User: "olivere",
- Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Image: "http://golang.org/doc/gopher/gophercolor.png",
- Tags: []string{"golang", "elasticsearch"},
- Location: "48.1333,11.5667", // lat,lon
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere",
- Retweets: 0,
- Message: "Another unrelated topic.",
- Tags: []string{"golang"},
- Location: "48.1189,11.4289", // lat,lon
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae",
- Retweets: 12,
- Message: "Cycling is fun.",
- Tags: []string{"sports", "cycling"},
- Location: "47.7167,11.7167", // lat,lon
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
-
- // Terms Aggregate by user name
- globalAgg := NewGlobalAggregation()
- usersAgg := NewTermsAggregation().Field("user").Size(10).OrderByCountDesc()
- retweetsAgg := NewTermsAggregation().Field("retweets").Size(10)
- avgRetweetsAgg := NewAvgAggregation().Field("retweets")
- avgRetweetsWithMetaAgg := NewAvgAggregation().Field("retweetsMeta").Meta(map[string]interface{}{"meta": true})
- minRetweetsAgg := NewMinAggregation().Field("retweets")
- maxRetweetsAgg := NewMaxAggregation().Field("retweets")
- sumRetweetsAgg := NewSumAggregation().Field("retweets")
- statsRetweetsAgg := NewStatsAggregation().Field("retweets")
- extstatsRetweetsAgg := NewExtendedStatsAggregation().Field("retweets")
- valueCountRetweetsAgg := NewValueCountAggregation().Field("retweets")
- percentilesRetweetsAgg := NewPercentilesAggregation().Field("retweets")
- percentileRanksRetweetsAgg := NewPercentileRanksAggregation().Field("retweets").Values(25, 50, 75)
- cardinalityAgg := NewCardinalityAggregation().Field("user")
- significantTermsAgg := NewSignificantTermsAggregation().Field("message")
- samplerAgg := NewSamplerAggregation().SubAggregation("tagged_with", NewTermsAggregation().Field("tags"))
- retweetsRangeAgg := NewRangeAggregation().Field("retweets").Lt(10).Between(10, 100).Gt(100)
- retweetsKeyedRangeAgg := NewRangeAggregation().Field("retweets").Keyed(true).Lt(10).Between(10, 100).Gt(100)
- dateRangeAgg := NewDateRangeAggregation().Field("created").Lt("2012-01-01").Between("2012-01-01", "2013-01-01").Gt("2013-01-01")
- missingTagsAgg := NewMissingAggregation().Field("tags")
- retweetsHistoAgg := NewHistogramAggregation().Field("retweets").Interval(100)
- dateHistoAgg := NewDateHistogramAggregation().Field("created").Interval("year")
- retweetsFilterAgg := NewFilterAggregation().Filter(
- NewRangeQuery("created").Gte("2012-01-01").Lte("2012-12-31")).
- SubAggregation("avgRetweetsSub", NewAvgAggregation().Field("retweets"))
- queryFilterAgg := NewFilterAggregation().Filter(NewTermQuery("tags", "golang"))
- topTagsHitsAgg := NewTopHitsAggregation().Sort("created", false).Size(5).FetchSource(true)
- topTagsAgg := NewTermsAggregation().Field("tags").Size(3).SubAggregation("top_tag_hits", topTagsHitsAgg)
- geoBoundsAgg := NewGeoBoundsAggregation().Field("location")
- geoHashAgg := NewGeoHashGridAggregation().Field("location").Precision(5)
- composite := NewCompositeAggregation().Sources(
- NewCompositeAggregationTermsValuesSource("composite_users").Field("user"),
- NewCompositeAggregationHistogramValuesSource("composite_retweets", 1).Field("retweets"),
- NewCompositeAggregationDateHistogramValuesSource("composite_created", "1m").Field("created"),
- )
-
- // Run query
- builder := client.Search().Index(testIndexName).Query(all).Pretty(true)
- builder = builder.Aggregation("global", globalAgg)
- builder = builder.Aggregation("users", usersAgg)
- builder = builder.Aggregation("retweets", retweetsAgg)
- builder = builder.Aggregation("avgRetweets", avgRetweetsAgg)
- builder = builder.Aggregation("avgRetweetsWithMeta", avgRetweetsWithMetaAgg)
- builder = builder.Aggregation("minRetweets", minRetweetsAgg)
- builder = builder.Aggregation("maxRetweets", maxRetweetsAgg)
- builder = builder.Aggregation("sumRetweets", sumRetweetsAgg)
- builder = builder.Aggregation("statsRetweets", statsRetweetsAgg)
- builder = builder.Aggregation("extstatsRetweets", extstatsRetweetsAgg)
- builder = builder.Aggregation("valueCountRetweets", valueCountRetweetsAgg)
- builder = builder.Aggregation("percentilesRetweets", percentilesRetweetsAgg)
- builder = builder.Aggregation("percentileRanksRetweets", percentileRanksRetweetsAgg)
- builder = builder.Aggregation("usersCardinality", cardinalityAgg)
- builder = builder.Aggregation("significantTerms", significantTermsAgg)
- builder = builder.Aggregation("sample", samplerAgg)
- builder = builder.Aggregation("retweetsRange", retweetsRangeAgg)
- builder = builder.Aggregation("retweetsKeyedRange", retweetsKeyedRangeAgg)
- builder = builder.Aggregation("dateRange", dateRangeAgg)
- builder = builder.Aggregation("missingTags", missingTagsAgg)
- builder = builder.Aggregation("retweetsHisto", retweetsHistoAgg)
- builder = builder.Aggregation("dateHisto", dateHistoAgg)
- builder = builder.Aggregation("retweetsFilter", retweetsFilterAgg)
- builder = builder.Aggregation("queryFilter", queryFilterAgg)
- builder = builder.Aggregation("top-tags", topTagsAgg)
- builder = builder.Aggregation("viewport", geoBoundsAgg)
- builder = builder.Aggregation("geohashed", geoHashAgg)
- // Unnamed filters
- countByUserAgg := NewFiltersAggregation().
- Filters(NewTermQuery("user", "olivere"), NewTermQuery("user", "sandrae"))
- builder = builder.Aggregation("countByUser", countByUserAgg)
- // Named filters
- countByUserAgg2 := NewFiltersAggregation().
- FilterWithName("olivere", NewTermQuery("user", "olivere")).
- FilterWithName("sandrae", NewTermQuery("user", "sandrae"))
- builder = builder.Aggregation("countByUser2", countByUserAgg2)
- // AvgBucket
- dateHisto := NewDateHistogramAggregation().Field("created").Interval("year")
- dateHisto = dateHisto.SubAggregation("sumOfRetweets", NewSumAggregation().Field("retweets"))
- builder = builder.Aggregation("avgBucketDateHisto", dateHisto)
- builder = builder.Aggregation("avgSumOfRetweets", NewAvgBucketAggregation().BucketsPath("avgBucketDateHisto>sumOfRetweets"))
- // MinBucket
- dateHisto = NewDateHistogramAggregation().Field("created").Interval("year")
- dateHisto = dateHisto.SubAggregation("sumOfRetweets", NewSumAggregation().Field("retweets"))
- builder = builder.Aggregation("minBucketDateHisto", dateHisto)
- builder = builder.Aggregation("minBucketSumOfRetweets", NewMinBucketAggregation().BucketsPath("minBucketDateHisto>sumOfRetweets"))
- // MaxBucket
- dateHisto = NewDateHistogramAggregation().Field("created").Interval("year")
- dateHisto = dateHisto.SubAggregation("sumOfRetweets", NewSumAggregation().Field("retweets"))
- builder = builder.Aggregation("maxBucketDateHisto", dateHisto)
- builder = builder.Aggregation("maxBucketSumOfRetweets", NewMaxBucketAggregation().BucketsPath("maxBucketDateHisto>sumOfRetweets"))
- // SumBucket
- dateHisto = NewDateHistogramAggregation().Field("created").Interval("year")
- dateHisto = dateHisto.SubAggregation("sumOfRetweets", NewSumAggregation().Field("retweets"))
- builder = builder.Aggregation("sumBucketDateHisto", dateHisto)
- builder = builder.Aggregation("sumBucketSumOfRetweets", NewSumBucketAggregation().BucketsPath("sumBucketDateHisto>sumOfRetweets"))
- // MovAvg
- dateHisto = NewDateHistogramAggregation().Field("created").Interval("year")
- dateHisto = dateHisto.SubAggregation("sumOfRetweets", NewSumAggregation().Field("retweets"))
- dateHisto = dateHisto.SubAggregation("movingAvg", NewMovAvgAggregation().BucketsPath("sumOfRetweets"))
- builder = builder.Aggregation("movingAvgDateHisto", dateHisto)
- builder = builder.Aggregation("composite", composite)
- searchResult, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected Hits != nil; got: nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected Hits.TotalHits = %d; got: %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 3 {
- t.Errorf("expected len(Hits.Hits) = %d; got: %d", 3, len(searchResult.Hits.Hits))
- }
- agg := searchResult.Aggregations
- if agg == nil {
- t.Fatalf("expected Aggregations != nil; got: nil")
- }
-
- // Search for non-existent aggregate should return (nil, false)
- unknownAgg, found := agg.Terms("no-such-aggregate")
- if found {
- t.Errorf("expected unknown aggregation to not be found; got: %v", found)
- }
- if unknownAgg != nil {
- t.Errorf("expected unknown aggregation to return %v; got %v", nil, unknownAgg)
- }
-
- // Global
- globalAggRes, found := agg.Global("global")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if globalAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if globalAggRes.DocCount != 3 {
- t.Errorf("expected DocCount = %d; got: %d", 3, globalAggRes.DocCount)
- }
-
- // Search for existent aggregate (by name) should return (aggregate, true)
- termsAggRes, found := agg.Terms("users")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if termsAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(termsAggRes.Buckets) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(termsAggRes.Buckets))
- }
- if termsAggRes.Buckets[0].Key != "olivere" {
- t.Errorf("expected %q; got: %q", "olivere", termsAggRes.Buckets[0].Key)
- }
- if termsAggRes.Buckets[0].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, termsAggRes.Buckets[0].DocCount)
- }
- if termsAggRes.Buckets[1].Key != "sandrae" {
- t.Errorf("expected %q; got: %q", "sandrae", termsAggRes.Buckets[1].Key)
- }
- if termsAggRes.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, termsAggRes.Buckets[1].DocCount)
- }
-
- // A terms aggregate with keys that are not strings
- retweetsAggRes, found := agg.Terms("retweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if retweetsAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(retweetsAggRes.Buckets) != 3 {
- t.Fatalf("expected %d; got: %d", 3, len(retweetsAggRes.Buckets))
- }
-
- if retweetsAggRes.Buckets[0].Key != float64(0) {
- t.Errorf("expected %v; got: %v", float64(0), retweetsAggRes.Buckets[0].Key)
- }
- if got, err := retweetsAggRes.Buckets[0].KeyNumber.Int64(); err != nil {
- t.Errorf("expected %d; got: %v", 0, retweetsAggRes.Buckets[0].Key)
- } else if got != 0 {
- t.Errorf("expected %d; got: %d", 0, got)
- }
- if retweetsAggRes.Buckets[0].KeyNumber != "0" {
- t.Errorf("expected %q; got: %q", "0", retweetsAggRes.Buckets[0].KeyNumber)
- }
- if retweetsAggRes.Buckets[0].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, retweetsAggRes.Buckets[0].DocCount)
- }
-
- if retweetsAggRes.Buckets[1].Key != float64(12) {
- t.Errorf("expected %v; got: %v", float64(12), retweetsAggRes.Buckets[1].Key)
- }
- if got, err := retweetsAggRes.Buckets[1].KeyNumber.Int64(); err != nil {
- t.Errorf("expected %d; got: %v", 0, retweetsAggRes.Buckets[1].KeyNumber)
- } else if got != 12 {
- t.Errorf("expected %d; got: %d", 12, got)
- }
- if retweetsAggRes.Buckets[1].KeyNumber != "12" {
- t.Errorf("expected %q; got: %q", "12", retweetsAggRes.Buckets[1].KeyNumber)
- }
- if retweetsAggRes.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, retweetsAggRes.Buckets[1].DocCount)
- }
-
- if retweetsAggRes.Buckets[2].Key != float64(108) {
- t.Errorf("expected %v; got: %v", float64(108), retweetsAggRes.Buckets[2].Key)
- }
- if got, err := retweetsAggRes.Buckets[2].KeyNumber.Int64(); err != nil {
- t.Errorf("expected %d; got: %v", 108, retweetsAggRes.Buckets[2].KeyNumber)
- } else if got != 108 {
- t.Errorf("expected %d; got: %d", 108, got)
- }
- if retweetsAggRes.Buckets[2].KeyNumber != "108" {
- t.Errorf("expected %q; got: %q", "108", retweetsAggRes.Buckets[2].KeyNumber)
- }
- if retweetsAggRes.Buckets[2].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, retweetsAggRes.Buckets[2].DocCount)
- }
-
- // avgRetweets
- avgAggRes, found := agg.Avg("avgRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if avgAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if avgAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *avgAggRes.Value)
- }
- if *avgAggRes.Value != 40.0 {
- t.Errorf("expected %v; got: %v", 40.0, *avgAggRes.Value)
- }
-
- // avgRetweetsWithMeta
- avgMetaAggRes, found := agg.Avg("avgRetweetsWithMeta")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if avgMetaAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if avgMetaAggRes.Meta == nil {
- t.Fatalf("expected != nil; got: %v", avgMetaAggRes.Meta)
- }
- metaDataValue, found := avgMetaAggRes.Meta["meta"]
- if !found {
- t.Fatalf("expected to return meta data key %q; got: %v", "meta", found)
- }
- if flag, ok := metaDataValue.(bool); !ok {
- t.Fatalf("expected to return meta data key type %T; got: %T", true, metaDataValue)
- } else if flag != true {
- t.Fatalf("expected to return meta data key value %v; got: %v", true, flag)
- }
-
- // minRetweets
- minAggRes, found := agg.Min("minRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if minAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if minAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *minAggRes.Value)
- }
- if *minAggRes.Value != 0.0 {
- t.Errorf("expected %v; got: %v", 0.0, *minAggRes.Value)
- }
-
- // maxRetweets
- maxAggRes, found := agg.Max("maxRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if maxAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if maxAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *maxAggRes.Value)
- }
- if *maxAggRes.Value != 108.0 {
- t.Errorf("expected %v; got: %v", 108.0, *maxAggRes.Value)
- }
-
- // sumRetweets
- sumAggRes, found := agg.Sum("sumRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if sumAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if sumAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *sumAggRes.Value)
- }
- if *sumAggRes.Value != 120.0 {
- t.Errorf("expected %v; got: %v", 120.0, *sumAggRes.Value)
- }
-
- // statsRetweets
- statsAggRes, found := agg.Stats("statsRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if statsAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if statsAggRes.Count != 3 {
- t.Errorf("expected %d; got: %d", 3, statsAggRes.Count)
- }
- if statsAggRes.Min == nil {
- t.Fatalf("expected != nil; got: %v", *statsAggRes.Min)
- }
- if *statsAggRes.Min != 0.0 {
- t.Errorf("expected %v; got: %v", 0.0, *statsAggRes.Min)
- }
- if statsAggRes.Max == nil {
- t.Fatalf("expected != nil; got: %v", *statsAggRes.Max)
- }
- if *statsAggRes.Max != 108.0 {
- t.Errorf("expected %v; got: %v", 108.0, *statsAggRes.Max)
- }
- if statsAggRes.Avg == nil {
- t.Fatalf("expected != nil; got: %v", *statsAggRes.Avg)
- }
- if *statsAggRes.Avg != 40.0 {
- t.Errorf("expected %v; got: %v", 40.0, *statsAggRes.Avg)
- }
- if statsAggRes.Sum == nil {
- t.Fatalf("expected != nil; got: %v", *statsAggRes.Sum)
- }
- if *statsAggRes.Sum != 120.0 {
- t.Errorf("expected %v; got: %v", 120.0, *statsAggRes.Sum)
- }
-
- // extstatsRetweets
- extStatsAggRes, found := agg.ExtendedStats("extstatsRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if extStatsAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if extStatsAggRes.Count != 3 {
- t.Errorf("expected %d; got: %d", 3, extStatsAggRes.Count)
- }
- if extStatsAggRes.Min == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.Min)
- }
- if *extStatsAggRes.Min != 0.0 {
- t.Errorf("expected %v; got: %v", 0.0, *extStatsAggRes.Min)
- }
- if extStatsAggRes.Max == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.Max)
- }
- if *extStatsAggRes.Max != 108.0 {
- t.Errorf("expected %v; got: %v", 108.0, *extStatsAggRes.Max)
- }
- if extStatsAggRes.Avg == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.Avg)
- }
- if *extStatsAggRes.Avg != 40.0 {
- t.Errorf("expected %v; got: %v", 40.0, *extStatsAggRes.Avg)
- }
- if extStatsAggRes.Sum == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.Sum)
- }
- if *extStatsAggRes.Sum != 120.0 {
- t.Errorf("expected %v; got: %v", 120.0, *extStatsAggRes.Sum)
- }
- if extStatsAggRes.SumOfSquares == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.SumOfSquares)
- }
- if *extStatsAggRes.SumOfSquares != 11808.0 {
- t.Errorf("expected %v; got: %v", 11808.0, *extStatsAggRes.SumOfSquares)
- }
- if extStatsAggRes.Variance == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.Variance)
- }
- if *extStatsAggRes.Variance != 2336.0 {
- t.Errorf("expected %v; got: %v", 2336.0, *extStatsAggRes.Variance)
- }
- if extStatsAggRes.StdDeviation == nil {
- t.Fatalf("expected != nil; got: %v", *extStatsAggRes.StdDeviation)
- }
- if *extStatsAggRes.StdDeviation != 48.33218389437829 {
- t.Errorf("expected %v; got: %v", 48.33218389437829, *extStatsAggRes.StdDeviation)
- }
-
- // valueCountRetweets
- valueCountAggRes, found := agg.ValueCount("valueCountRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if valueCountAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if valueCountAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *valueCountAggRes.Value)
- }
- if *valueCountAggRes.Value != 3.0 {
- t.Errorf("expected %v; got: %v", 3.0, *valueCountAggRes.Value)
- }
-
- // percentilesRetweets
- percentilesAggRes, found := agg.Percentiles("percentilesRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if percentilesAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- // ES 1.4.x returns 7: {"1.0":...}
- // ES 1.5.0 returns 14: {"1.0":..., "1.0_as_string":...}
- // So we're relaxing the test here.
- if len(percentilesAggRes.Values) == 0 {
- t.Errorf("expected at least %d value; got: %d\nValues are: %#v", 1, len(percentilesAggRes.Values), percentilesAggRes.Values)
- }
- if _, found := percentilesAggRes.Values["0.0"]; found {
- t.Errorf("expected %v; got: %v", false, found)
- }
- if percentilesAggRes.Values["1.0"] != 0.24 {
- t.Errorf("expected %v; got: %v", 0.24, percentilesAggRes.Values["1.0"])
- }
- if percentilesAggRes.Values["25.0"] != 6.0 {
- t.Errorf("expected %v; got: %v", 6.0, percentilesAggRes.Values["25.0"])
- }
- if percentilesAggRes.Values["99.0"] != 106.08 {
- t.Errorf("expected %v; got: %v", 106.08, percentilesAggRes.Values["99.0"])
- }
-
- // percentileRanksRetweets
- percentileRanksAggRes, found := agg.PercentileRanks("percentileRanksRetweets")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if percentileRanksAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(percentileRanksAggRes.Values) == 0 {
- t.Errorf("expected at least %d value; got %d\nValues are: %#v", 1, len(percentileRanksAggRes.Values), percentileRanksAggRes.Values)
- }
- if _, found := percentileRanksAggRes.Values["0.0"]; found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if percentileRanksAggRes.Values["25.0"] != 21.180555555555557 {
- t.Errorf("expected %v; got: %v", 21.180555555555557, percentileRanksAggRes.Values["25.0"])
- }
- if percentileRanksAggRes.Values["50.0"] != 29.86111111111111 {
- t.Errorf("expected %v; got: %v", 29.86111111111111, percentileRanksAggRes.Values["50.0"])
- }
- if percentileRanksAggRes.Values["75.0"] != 38.54166666666667 {
- t.Errorf("expected %v; got: %v", 38.54166666666667, percentileRanksAggRes.Values["75.0"])
- }
-
- // usersCardinality
- cardAggRes, found := agg.Cardinality("usersCardinality")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if cardAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if cardAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", *cardAggRes.Value)
- }
- if *cardAggRes.Value != 2 {
- t.Errorf("expected %v; got: %v", 2, *cardAggRes.Value)
- }
-
- // retweetsFilter
- filterAggRes, found := agg.Filter("retweetsFilter")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if filterAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if filterAggRes.DocCount != 2 {
- t.Fatalf("expected %v; got: %v", 2, filterAggRes.DocCount)
- }
-
- // Retrieve sub-aggregation
- avgRetweetsAggRes, found := filterAggRes.Avg("avgRetweetsSub")
- if !found {
- t.Error("expected sub-aggregation \"avgRetweets\" to be found; got false")
- }
- if avgRetweetsAggRes == nil {
- t.Fatal("expected sub-aggregation \"avgRetweets\"; got nil")
- }
- if avgRetweetsAggRes.Value == nil {
- t.Fatalf("expected != nil; got: %v", avgRetweetsAggRes.Value)
- }
- if *avgRetweetsAggRes.Value != 54.0 {
- t.Errorf("expected %v; got: %v", 54.0, *avgRetweetsAggRes.Value)
- }
-
- // queryFilter
- queryFilterAggRes, found := agg.Filter("queryFilter")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if queryFilterAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if queryFilterAggRes.DocCount != 2 {
- t.Fatalf("expected %v; got: %v", 2, queryFilterAggRes.DocCount)
- }
-
- // significantTerms
- stAggRes, found := agg.SignificantTerms("significantTerms")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if stAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if stAggRes.DocCount != 3 {
- t.Errorf("expected %v; got: %v", 3, stAggRes.DocCount)
- }
- if len(stAggRes.Buckets) != 0 {
- t.Errorf("expected %v; got: %v", 0, len(stAggRes.Buckets))
- }
-
- // sampler
- samplerAggRes, found := agg.Sampler("sample")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if samplerAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if samplerAggRes.DocCount != 3 {
- t.Errorf("expected %v; got: %v", 3, samplerAggRes.DocCount)
- }
- sub, found := samplerAggRes.Aggregations["tagged_with"]
- if !found {
- t.Fatalf("expected sub aggregation %q", "tagged_with")
- }
- if sub == nil {
- t.Fatalf("expected sub aggregation %q; got: %v", "tagged_with", sub)
- }
-
- // retweetsRange
- rangeAggRes, found := agg.Range("retweetsRange")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if rangeAggRes == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if len(rangeAggRes.Buckets) != 3 {
- t.Fatalf("expected %d; got: %d", 3, len(rangeAggRes.Buckets))
- }
- if rangeAggRes.Buckets[0].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, rangeAggRes.Buckets[0].DocCount)
- }
- if rangeAggRes.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, rangeAggRes.Buckets[1].DocCount)
- }
- if rangeAggRes.Buckets[2].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, rangeAggRes.Buckets[2].DocCount)
- }
-
- // retweetsKeyedRange
- keyedRangeAggRes, found := agg.KeyedRange("retweetsKeyedRange")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if keyedRangeAggRes == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if len(keyedRangeAggRes.Buckets) != 3 {
- t.Fatalf("expected %d; got: %d", 3, len(keyedRangeAggRes.Buckets))
- }
- _, found = keyedRangeAggRes.Buckets["no-such-key"]
- if found {
- t.Fatalf("expected bucket to not be found; got: %v", found)
- }
- bucket, found := keyedRangeAggRes.Buckets["*-10.0"]
- if !found {
- t.Fatalf("expected bucket to be found; got: %v", found)
- }
- if bucket.DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, bucket.DocCount)
- }
- bucket, found = keyedRangeAggRes.Buckets["10.0-100.0"]
- if !found {
- t.Fatalf("expected bucket to be found; got: %v", found)
- }
- if bucket.DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, bucket.DocCount)
- }
- bucket, found = keyedRangeAggRes.Buckets["100.0-*"]
- if !found {
- t.Fatalf("expected bucket to be found; got: %v", found)
- }
- if bucket.DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, bucket.DocCount)
- }
-
- // dateRange
- dateRangeRes, found := agg.DateRange("dateRange")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if dateRangeRes == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if dateRangeRes.Buckets[0].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, dateRangeRes.Buckets[0].DocCount)
- }
- if dateRangeRes.Buckets[0].From != nil {
- t.Fatal("expected From to be nil")
- }
- if dateRangeRes.Buckets[0].To == nil {
- t.Fatal("expected To to be != nil")
- }
- if *dateRangeRes.Buckets[0].To != 1.325376e+12 {
- t.Errorf("expected %v; got: %v", 1.325376e+12, *dateRangeRes.Buckets[0].To)
- }
- if dateRangeRes.Buckets[0].ToAsString != "2012-01-01T00:00:00.000Z" {
- t.Errorf("expected %q; got: %q", "2012-01-01T00:00:00.000Z", dateRangeRes.Buckets[0].ToAsString)
- }
- if dateRangeRes.Buckets[1].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, dateRangeRes.Buckets[1].DocCount)
- }
- if dateRangeRes.Buckets[1].From == nil {
- t.Fatal("expected From to be != nil")
- }
- if *dateRangeRes.Buckets[1].From != 1.325376e+12 {
- t.Errorf("expected From = %v; got: %v", 1.325376e+12, *dateRangeRes.Buckets[1].From)
- }
- if dateRangeRes.Buckets[1].FromAsString != "2012-01-01T00:00:00.000Z" {
- t.Errorf("expected FromAsString = %q; got: %q", "2012-01-01T00:00:00.000Z", dateRangeRes.Buckets[1].FromAsString)
- }
- if dateRangeRes.Buckets[1].To == nil {
- t.Fatal("expected To to be != nil")
- }
- if *dateRangeRes.Buckets[1].To != 1.3569984e+12 {
- t.Errorf("expected To = %v; got: %v", 1.3569984e+12, *dateRangeRes.Buckets[1].To)
- }
- if dateRangeRes.Buckets[1].ToAsString != "2013-01-01T00:00:00.000Z" {
- t.Errorf("expected ToAsString = %q; got: %q", "2013-01-01T00:00:00.000Z", dateRangeRes.Buckets[1].ToAsString)
- }
- if dateRangeRes.Buckets[2].DocCount != 0 {
- t.Errorf("expected %d; got: %d", 0, dateRangeRes.Buckets[2].DocCount)
- }
- if dateRangeRes.Buckets[2].To != nil {
- t.Fatal("expected To to be nil")
- }
- if dateRangeRes.Buckets[2].From == nil {
- t.Fatal("expected From to be != nil")
- }
- if *dateRangeRes.Buckets[2].From != 1.3569984e+12 {
- t.Errorf("expected %v; got: %v", 1.3569984e+12, *dateRangeRes.Buckets[2].From)
- }
- if dateRangeRes.Buckets[2].FromAsString != "2013-01-01T00:00:00.000Z" {
- t.Errorf("expected %q; got: %q", "2013-01-01T00:00:00.000Z", dateRangeRes.Buckets[2].FromAsString)
- }
-
- // missingTags
- missingRes, found := agg.Missing("missingTags")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if missingRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if missingRes.DocCount != 0 {
- t.Errorf("expected searchResult.Aggregations[\"missingTags\"].DocCount = %v; got %v", 0, missingRes.DocCount)
- }
-
- // retweetsHisto
- histoRes, found := agg.Histogram("retweetsHisto")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if histoRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(histoRes.Buckets) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(histoRes.Buckets))
- }
- if histoRes.Buckets[0].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, histoRes.Buckets[0].DocCount)
- }
- if histoRes.Buckets[0].Key != 0.0 {
- t.Errorf("expected %v; got: %v", 0.0, histoRes.Buckets[0].Key)
- }
- if histoRes.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, histoRes.Buckets[1].DocCount)
- }
- if histoRes.Buckets[1].Key != 100.0 {
- t.Errorf("expected %v; got: %+v", 100.0, histoRes.Buckets[1].Key)
- }
-
- // dateHisto
- dateHistoRes, found := agg.DateHistogram("dateHisto")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if dateHistoRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(dateHistoRes.Buckets) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(dateHistoRes.Buckets))
- }
- if dateHistoRes.Buckets[0].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, dateHistoRes.Buckets[0].DocCount)
- }
- if dateHistoRes.Buckets[0].Key != 1.29384e+12 {
- t.Errorf("expected %v; got: %v", 1.29384e+12, dateHistoRes.Buckets[0].Key)
- }
- if dateHistoRes.Buckets[0].KeyAsString == nil {
- t.Fatalf("expected != nil; got: %q", dateHistoRes.Buckets[0].KeyAsString)
- }
- if *dateHistoRes.Buckets[0].KeyAsString != "2011-01-01T00:00:00.000Z" {
- t.Errorf("expected %q; got: %q", "2011-01-01T00:00:00.000Z", *dateHistoRes.Buckets[0].KeyAsString)
- }
- if dateHistoRes.Buckets[1].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, dateHistoRes.Buckets[1].DocCount)
- }
- if dateHistoRes.Buckets[1].Key != 1.325376e+12 {
- t.Errorf("expected %v; got: %v", 1.325376e+12, dateHistoRes.Buckets[1].Key)
- }
- if dateHistoRes.Buckets[1].KeyAsString == nil {
- t.Fatalf("expected != nil; got: %q", dateHistoRes.Buckets[1].KeyAsString)
- }
- if *dateHistoRes.Buckets[1].KeyAsString != "2012-01-01T00:00:00.000Z" {
- t.Errorf("expected %q; got: %q", "2012-01-01T00:00:00.000Z", *dateHistoRes.Buckets[1].KeyAsString)
- }
-
- // topHits
- topTags, found := agg.Terms("top-tags")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if topTags == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if topTags.DocCountErrorUpperBound != 0 {
- t.Errorf("expected %v; got: %v", 0, topTags.DocCountErrorUpperBound)
- }
- if topTags.SumOfOtherDocCount != 1 {
- t.Errorf("expected %v; got: %v", 1, topTags.SumOfOtherDocCount)
- }
- if len(topTags.Buckets) != 3 {
- t.Fatalf("expected %d; got: %d", 3, len(topTags.Buckets))
- }
- if topTags.Buckets[0].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, topTags.Buckets[0].DocCount)
- }
- if topTags.Buckets[0].Key != "golang" {
- t.Errorf("expected %v; got: %v", "golang", topTags.Buckets[0].Key)
- }
- topHits, found := topTags.Buckets[0].TopHits("top_tag_hits")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if topHits == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if topHits.Hits == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if topHits.Hits.TotalHits != 2 {
- t.Errorf("expected %d; got: %d", 2, topHits.Hits.TotalHits)
- }
- if topHits.Hits.Hits == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(topHits.Hits.Hits) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(topHits.Hits.Hits))
- }
- hit := topHits.Hits.Hits[0]
- if !found {
- t.Fatalf("expected %v; got: %v", true, found)
- }
- if hit == nil {
- t.Fatal("expected != nil; got: nil")
- }
- var tw tweet
- if err := json.Unmarshal(*hit.Source, &tw); err != nil {
- t.Fatalf("expected no error; got: %v", err)
- }
- if tw.Message != "Welcome to Golang and Elasticsearch." {
- t.Errorf("expected %q; got: %q", "Welcome to Golang and Elasticsearch.", tw.Message)
- }
- if topTags.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, topTags.Buckets[1].DocCount)
- }
- if topTags.Buckets[1].Key != "cycling" {
- t.Errorf("expected %v; got: %v", "cycling", topTags.Buckets[1].Key)
- }
- topHits, found = topTags.Buckets[1].TopHits("top_tag_hits")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if topHits == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if topHits.Hits == nil {
- t.Fatal("expected != nil; got nil")
- }
- if topHits.Hits.TotalHits != 1 {
- t.Errorf("expected %d; got: %d", 1, topHits.Hits.TotalHits)
- }
- if topTags.Buckets[2].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, topTags.Buckets[2].DocCount)
- }
- if topTags.Buckets[2].Key != "elasticsearch" {
- t.Errorf("expected %v; got: %v", "elasticsearch", topTags.Buckets[2].Key)
- }
- topHits, found = topTags.Buckets[2].TopHits("top_tag_hits")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if topHits == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if topHits.Hits == nil {
- t.Fatal("expected != nil; got: nil")
- }
- if topHits.Hits.TotalHits != 1 {
- t.Errorf("expected %d; got: %d", 1, topHits.Hits.TotalHits)
- }
-
- // viewport via geo_bounds (1.3.0 has an error in that it doesn't output the aggregation name)
- geoBoundsRes, found := agg.GeoBounds("viewport")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if geoBoundsRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
-
- // geohashed via geohash
- geoHashRes, found := agg.GeoHash("geohashed")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if geoHashRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
-
- // Filters agg "countByUser" (unnamed)
- countByUserAggRes, found := agg.Filters("countByUser")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if countByUserAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(countByUserAggRes.Buckets) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(countByUserAggRes.Buckets))
- }
- if len(countByUserAggRes.NamedBuckets) != 0 {
- t.Fatalf("expected %d; got: %d", 0, len(countByUserAggRes.NamedBuckets))
- }
- if countByUserAggRes.Buckets[0].DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, countByUserAggRes.Buckets[0].DocCount)
- }
- if countByUserAggRes.Buckets[1].DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, countByUserAggRes.Buckets[1].DocCount)
- }
-
- // Filters agg "countByUser2" (named)
- countByUser2AggRes, found := agg.Filters("countByUser2")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if countByUser2AggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if len(countByUser2AggRes.Buckets) != 0 {
- t.Fatalf("expected %d; got: %d", 0, len(countByUser2AggRes.Buckets))
- }
- if len(countByUser2AggRes.NamedBuckets) != 2 {
- t.Fatalf("expected %d; got: %d", 2, len(countByUser2AggRes.NamedBuckets))
- }
- b, found := countByUser2AggRes.NamedBuckets["olivere"]
- if !found {
- t.Fatalf("expected bucket %q; got: %v", "olivere", found)
- }
- if b == nil {
- t.Fatalf("expected bucket %q; got: %v", "olivere", b)
- }
- if b.DocCount != 2 {
- t.Errorf("expected %d; got: %d", 2, b.DocCount)
- }
- b, found = countByUser2AggRes.NamedBuckets["sandrae"]
- if !found {
- t.Fatalf("expected bucket %q; got: %v", "sandrae", found)
- }
- if b == nil {
- t.Fatalf("expected bucket %q; got: %v", "sandrae", b)
- }
- if b.DocCount != 1 {
- t.Errorf("expected %d; got: %d", 1, b.DocCount)
- }
-
- compositeAggRes, found := agg.Composite("composite")
- if !found {
- t.Errorf("expected %v; got: %v", true, found)
- }
- if compositeAggRes == nil {
- t.Fatalf("expected != nil; got: nil")
- }
- if want, have := 3, len(compositeAggRes.Buckets); want != have {
- t.Fatalf("expected %d; got: %d", want, have)
- }
-}
-
-// TestAggsMarshal ensures that marshaling aggregations back into a string
-// does not yield base64 encoded data. See https://github.com/olivere/elastic/issues/51
-// and https://groups.google.com/forum/#!topic/Golang-Nuts/38ShOlhxAYY for details.
-func TestAggsMarshal(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere",
- Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Image: "http://golang.org/doc/gopher/gophercolor.png",
- Tags: []string{"golang", "elasticsearch"},
- Location: "48.1333,11.5667", // lat,lon
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- dhagg := NewDateHistogramAggregation().Field("created").Interval("year")
-
- // Run query
- builder := client.Search().Index(testIndexName).Query(all)
- builder = builder.Aggregation("dhagg", dhagg)
- searchResult, err := builder.Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.TotalHits() != 1 {
- t.Errorf("expected Hits.TotalHits = %d; got: %d", 1, searchResult.TotalHits())
- }
- if _, found := searchResult.Aggregations["dhagg"]; !found {
- t.Fatalf("expected aggregation %q", "dhagg")
- }
- buf, err := json.Marshal(searchResult)
- if err != nil {
- t.Fatal(err)
- }
- s := string(buf)
- if i := strings.Index(s, `{"dhagg":{"buckets":[{"key_as_string":"2012-01-01`); i < 0 {
- t.Errorf("expected to serialize aggregation into string; got: %v", s)
- }
-}
-
-func TestAggsMetricsMin(t *testing.T) {
- s := `{
- "min_price": {
- "value": 10
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Min("min_price")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(10) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(10), *agg.Value)
- }
-}
-
-func TestAggsMetricsMax(t *testing.T) {
- s := `{
- "max_price": {
- "value": 35
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Max("max_price")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(35) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(35), *agg.Value)
- }
-}
-
-func TestAggsMetricsSum(t *testing.T) {
- s := `{
- "intraday_return": {
- "value": 2.18
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Sum("intraday_return")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(2.18) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(2.18), *agg.Value)
- }
-}
-
-func TestAggsMetricsAvg(t *testing.T) {
- s := `{
- "avg_grade": {
- "value": 75
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Avg("avg_grade")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(75) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(75), *agg.Value)
- }
-}
-
-func TestAggsMetricsValueCount(t *testing.T) {
- s := `{
- "grades_count": {
- "value": 10
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.ValueCount("grades_count")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(10) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(10), *agg.Value)
- }
-}
-
-func TestAggsMetricsCardinality(t *testing.T) {
- s := `{
- "author_count": {
- "value": 12
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Cardinality("author_count")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(12) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(12), *agg.Value)
- }
-}
-
-func TestAggsMetricsStats(t *testing.T) {
- s := `{
- "grades_stats": {
- "count": 6,
- "min": 60,
- "max": 98,
- "avg": 78.5,
- "sum": 471
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Stats("grades_stats")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Count != int64(6) {
- t.Fatalf("expected aggregation Count = %v; got: %v", int64(6), agg.Count)
- }
- if agg.Min == nil {
- t.Fatalf("expected aggregation Min != nil; got: %v", agg.Min)
- }
- if *agg.Min != float64(60) {
- t.Fatalf("expected aggregation Min = %v; got: %v", float64(60), *agg.Min)
- }
- if agg.Max == nil {
- t.Fatalf("expected aggregation Max != nil; got: %v", agg.Max)
- }
- if *agg.Max != float64(98) {
- t.Fatalf("expected aggregation Max = %v; got: %v", float64(98), *agg.Max)
- }
- if agg.Avg == nil {
- t.Fatalf("expected aggregation Avg != nil; got: %v", agg.Avg)
- }
- if *agg.Avg != float64(78.5) {
- t.Fatalf("expected aggregation Avg = %v; got: %v", float64(78.5), *agg.Avg)
- }
- if agg.Sum == nil {
- t.Fatalf("expected aggregation Sum != nil; got: %v", agg.Sum)
- }
- if *agg.Sum != float64(471) {
- t.Fatalf("expected aggregation Sum = %v; got: %v", float64(471), *agg.Sum)
- }
-}
-
-func TestAggsMetricsExtendedStats(t *testing.T) {
- s := `{
- "grades_stats": {
- "count": 6,
- "min": 72,
- "max": 117.6,
- "avg": 94.2,
- "sum": 565.2,
- "sum_of_squares": 54551.51999999999,
- "variance": 218.2799999999976,
- "std_deviation": 14.774302013969987
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.ExtendedStats("grades_stats")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Count != int64(6) {
- t.Fatalf("expected aggregation Count = %v; got: %v", int64(6), agg.Count)
- }
- if agg.Min == nil {
- t.Fatalf("expected aggregation Min != nil; got: %v", agg.Min)
- }
- if *agg.Min != float64(72) {
- t.Fatalf("expected aggregation Min = %v; got: %v", float64(72), *agg.Min)
- }
- if agg.Max == nil {
- t.Fatalf("expected aggregation Max != nil; got: %v", agg.Max)
- }
- if *agg.Max != float64(117.6) {
- t.Fatalf("expected aggregation Max = %v; got: %v", float64(117.6), *agg.Max)
- }
- if agg.Avg == nil {
- t.Fatalf("expected aggregation Avg != nil; got: %v", agg.Avg)
- }
- if *agg.Avg != float64(94.2) {
- t.Fatalf("expected aggregation Avg = %v; got: %v", float64(94.2), *agg.Avg)
- }
- if agg.Sum == nil {
- t.Fatalf("expected aggregation Sum != nil; got: %v", agg.Sum)
- }
- if *agg.Sum != float64(565.2) {
- t.Fatalf("expected aggregation Sum = %v; got: %v", float64(565.2), *agg.Sum)
- }
- if agg.SumOfSquares == nil {
- t.Fatalf("expected aggregation sum_of_squares != nil; got: %v", agg.SumOfSquares)
- }
- if *agg.SumOfSquares != float64(54551.51999999999) {
- t.Fatalf("expected aggregation sum_of_squares = %v; got: %v", float64(54551.51999999999), *agg.SumOfSquares)
- }
- if agg.Variance == nil {
- t.Fatalf("expected aggregation Variance != nil; got: %v", agg.Variance)
- }
- if *agg.Variance != float64(218.2799999999976) {
- t.Fatalf("expected aggregation Variance = %v; got: %v", float64(218.2799999999976), *agg.Variance)
- }
- if agg.StdDeviation == nil {
- t.Fatalf("expected aggregation StdDeviation != nil; got: %v", agg.StdDeviation)
- }
- if *agg.StdDeviation != float64(14.774302013969987) {
- t.Fatalf("expected aggregation StdDeviation = %v; got: %v", float64(14.774302013969987), *agg.StdDeviation)
- }
-}
-
-func TestAggsMatrixStats(t *testing.T) {
- s := `{
- "matrixstats": {
- "fields": [{
- "name": "income",
- "count": 50,
- "mean": 51985.1,
- "variance": 7.383377037755103E7,
- "skewness": 0.5595114003506483,
- "kurtosis": 2.5692365287787124,
- "covariance": {
- "income": 7.383377037755103E7,
- "poverty": -21093.65836734694
- },
- "correlation": {
- "income": 1.0,
- "poverty": -0.8352655256272504
- }
- }, {
- "name": "poverty",
- "count": 51,
- "mean": 12.732000000000001,
- "variance": 8.637730612244896,
- "skewness": 0.4516049811903419,
- "kurtosis": 2.8615929677997767,
- "covariance": {
- "income": -21093.65836734694,
- "poverty": 8.637730612244896
- },
- "correlation": {
- "income": -0.8352655256272504,
- "poverty": 1.0
- }
- }]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.MatrixStats("matrixstats")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if want, got := 2, len(agg.Fields); want != got {
- t.Fatalf("expected aggregaton len(Fields) = %v; got: %v", want, got)
- }
- field := agg.Fields[0]
- if want, got := "income", field.Name; want != got {
- t.Fatalf("expected aggregation field name == %q; got: %q", want, got)
- }
- if want, got := int64(50), field.Count; want != got {
- t.Fatalf("expected aggregation field count == %v; got: %v", want, got)
- }
- if want, got := 51985.1, field.Mean; want != got {
- t.Fatalf("expected aggregation field mean == %v; got: %v", want, got)
- }
- if want, got := 7.383377037755103e7, field.Variance; want != got {
- t.Fatalf("expected aggregation field variance == %v; got: %v", want, got)
- }
- if want, got := 0.5595114003506483, field.Skewness; want != got {
- t.Fatalf("expected aggregation field skewness == %v; got: %v", want, got)
- }
- if want, got := 2.5692365287787124, field.Kurtosis; want != got {
- t.Fatalf("expected aggregation field kurtosis == %v; got: %v", want, got)
- }
- if field.Covariance == nil {
- t.Fatalf("expected aggregation field covariance != nil; got: %v", nil)
- }
- if want, got := 7.383377037755103e7, field.Covariance["income"]; want != got {
- t.Fatalf("expected aggregation field covariance == %v; got: %v", want, got)
- }
- if want, got := -21093.65836734694, field.Covariance["poverty"]; want != got {
- t.Fatalf("expected aggregation field covariance == %v; got: %v", want, got)
- }
- if field.Correlation == nil {
- t.Fatalf("expected aggregation field correlation != nil; got: %v", nil)
- }
- if want, got := 1.0, field.Correlation["income"]; want != got {
- t.Fatalf("expected aggregation field correlation == %v; got: %v", want, got)
- }
- if want, got := -0.8352655256272504, field.Correlation["poverty"]; want != got {
- t.Fatalf("expected aggregation field correlation == %v; got: %v", want, got)
- }
- field = agg.Fields[1]
- if want, got := "poverty", field.Name; want != got {
- t.Fatalf("expected aggregation field name == %q; got: %q", want, got)
- }
- if want, got := int64(51), field.Count; want != got {
- t.Fatalf("expected aggregation field count == %v; got: %v", want, got)
- }
-}
-
-func TestAggsMetricsPercentiles(t *testing.T) {
- s := `{
- "load_time_outlier": {
- "values" : {
- "1.0": 15,
- "5.0": 20,
- "25.0": 23,
- "50.0": 25,
- "75.0": 29,
- "95.0": 60,
- "99.0": 150
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Percentiles("load_time_outlier")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Values == nil {
- t.Fatalf("expected aggregation Values != nil; got: %v", agg.Values)
- }
- if len(agg.Values) != 7 {
- t.Fatalf("expected %d aggregation Values; got: %d", 7, len(agg.Values))
- }
- if agg.Values["1.0"] != float64(15) {
- t.Errorf("expected aggregation value for \"1.0\" = %v; got: %v", float64(15), agg.Values["1.0"])
- }
- if agg.Values["5.0"] != float64(20) {
- t.Errorf("expected aggregation value for \"5.0\" = %v; got: %v", float64(20), agg.Values["5.0"])
- }
- if agg.Values["25.0"] != float64(23) {
- t.Errorf("expected aggregation value for \"25.0\" = %v; got: %v", float64(23), agg.Values["25.0"])
- }
- if agg.Values["50.0"] != float64(25) {
- t.Errorf("expected aggregation value for \"50.0\" = %v; got: %v", float64(25), agg.Values["50.0"])
- }
- if agg.Values["75.0"] != float64(29) {
- t.Errorf("expected aggregation value for \"75.0\" = %v; got: %v", float64(29), agg.Values["75.0"])
- }
- if agg.Values["95.0"] != float64(60) {
- t.Errorf("expected aggregation value for \"95.0\" = %v; got: %v", float64(60), agg.Values["95.0"])
- }
- if agg.Values["99.0"] != float64(150) {
- t.Errorf("expected aggregation value for \"99.0\" = %v; got: %v", float64(150), agg.Values["99.0"])
- }
-}
-
-func TestAggsMetricsPercentileRanks(t *testing.T) {
- s := `{
- "load_time_outlier": {
- "values" : {
- "15": 92,
- "30": 100
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.PercentileRanks("load_time_outlier")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Values == nil {
- t.Fatalf("expected aggregation Values != nil; got: %v", agg.Values)
- }
- if len(agg.Values) != 2 {
- t.Fatalf("expected %d aggregation Values; got: %d", 7, len(agg.Values))
- }
- if agg.Values["15"] != float64(92) {
- t.Errorf("expected aggregation value for \"15\" = %v; got: %v", float64(92), agg.Values["15"])
- }
- if agg.Values["30"] != float64(100) {
- t.Errorf("expected aggregation value for \"30\" = %v; got: %v", float64(100), agg.Values["30"])
- }
-}
-
-func TestAggsMetricsTopHits(t *testing.T) {
- s := `{
- "top-tags": {
- "buckets": [
- {
- "key": "windows-7",
- "doc_count": 25365,
- "top_tags_hits": {
- "hits": {
- "total": 25365,
- "max_score": 1,
- "hits": [
- {
- "_index": "stack",
- "_type": "question",
- "_id": "602679",
- "_score": 1,
- "_source": {
- "title": "Windows port opening"
- },
- "sort": [
- 1370143231177
- ]
- }
- ]
- }
- }
- },
- {
- "key": "linux",
- "doc_count": 18342,
- "top_tags_hits": {
- "hits": {
- "total": 18342,
- "max_score": 1,
- "hits": [
- {
- "_index": "stack",
- "_type": "question",
- "_id": "602672",
- "_score": 1,
- "_source": {
- "title": "Ubuntu RFID Screensaver lock-unlock"
- },
- "sort": [
- 1370143379747
- ]
- }
- ]
- }
- }
- },
- {
- "key": "windows",
- "doc_count": 18119,
- "top_tags_hits": {
- "hits": {
- "total": 18119,
- "max_score": 1,
- "hits": [
- {
- "_index": "stack",
- "_type": "question",
- "_id": "602678",
- "_score": 1,
- "_source": {
- "title": "If I change my computers date / time, what could be affected?"
- },
- "sort": [
- 1370142868283
- ]
- }
- ]
- }
- }
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Terms("top-tags")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 3 {
- t.Errorf("expected %d bucket entries; got: %d", 3, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != "windows-7" {
- t.Errorf("expected bucket key = %q; got: %q", "windows-7", agg.Buckets[0].Key)
- }
- if agg.Buckets[1].Key != "linux" {
- t.Errorf("expected bucket key = %q; got: %q", "linux", agg.Buckets[1].Key)
- }
- if agg.Buckets[2].Key != "windows" {
- t.Errorf("expected bucket key = %q; got: %q", "windows", agg.Buckets[2].Key)
- }
-
- // Sub-aggregation of top-hits
- subAgg, found := agg.Buckets[0].TopHits("top_tags_hits")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Hits == nil {
- t.Fatalf("expected sub aggregation Hits != nil; got: %v", subAgg.Hits)
- }
- if subAgg.Hits.TotalHits != 25365 {
- t.Fatalf("expected sub aggregation Hits.TotalHits = %d; got: %d", 25365, subAgg.Hits.TotalHits)
- }
- if subAgg.Hits.MaxScore == nil {
- t.Fatalf("expected sub aggregation Hits.MaxScore != %v; got: %v", nil, *subAgg.Hits.MaxScore)
- }
- if *subAgg.Hits.MaxScore != float64(1.0) {
- t.Fatalf("expected sub aggregation Hits.MaxScore = %v; got: %v", float64(1.0), *subAgg.Hits.MaxScore)
- }
-
- subAgg, found = agg.Buckets[1].TopHits("top_tags_hits")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Hits == nil {
- t.Fatalf("expected sub aggregation Hits != nil; got: %v", subAgg.Hits)
- }
- if subAgg.Hits.TotalHits != 18342 {
- t.Fatalf("expected sub aggregation Hits.TotalHits = %d; got: %d", 18342, subAgg.Hits.TotalHits)
- }
- if subAgg.Hits.MaxScore == nil {
- t.Fatalf("expected sub aggregation Hits.MaxScore != %v; got: %v", nil, *subAgg.Hits.MaxScore)
- }
- if *subAgg.Hits.MaxScore != float64(1.0) {
- t.Fatalf("expected sub aggregation Hits.MaxScore = %v; got: %v", float64(1.0), *subAgg.Hits.MaxScore)
- }
-
- subAgg, found = agg.Buckets[2].TopHits("top_tags_hits")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Hits == nil {
- t.Fatalf("expected sub aggregation Hits != nil; got: %v", subAgg.Hits)
- }
- if subAgg.Hits.TotalHits != 18119 {
- t.Fatalf("expected sub aggregation Hits.TotalHits = %d; got: %d", 18119, subAgg.Hits.TotalHits)
- }
- if subAgg.Hits.MaxScore == nil {
- t.Fatalf("expected sub aggregation Hits.MaxScore != %v; got: %v", nil, *subAgg.Hits.MaxScore)
- }
- if *subAgg.Hits.MaxScore != float64(1.0) {
- t.Fatalf("expected sub aggregation Hits.MaxScore = %v; got: %v", float64(1.0), *subAgg.Hits.MaxScore)
- }
-}
-
-func TestAggsBucketGlobal(t *testing.T) {
- s := `{
- "all_products" : {
- "doc_count" : 100,
- "avg_price" : {
- "value" : 56.3
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Global("all_products")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 100 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 100, agg.DocCount)
- }
-
- // Sub-aggregation
- subAgg, found := agg.Avg("avg_price")
- if !found {
- t.Fatalf("expected sub-aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub-aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Value == nil {
- t.Fatalf("expected sub-aggregation value != nil; got: %v", subAgg.Value)
- }
- if *subAgg.Value != float64(56.3) {
- t.Fatalf("expected sub-aggregation value = %v; got: %v", float64(56.3), *subAgg.Value)
- }
-}
-
-func TestAggsBucketFilter(t *testing.T) {
- s := `{
- "in_stock_products" : {
- "doc_count" : 100,
- "avg_price" : { "value" : 56.3 }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Filter("in_stock_products")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 100 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 100, agg.DocCount)
- }
-
- // Sub-aggregation
- subAgg, found := agg.Avg("avg_price")
- if !found {
- t.Fatalf("expected sub-aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub-aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Value == nil {
- t.Fatalf("expected sub-aggregation value != nil; got: %v", subAgg.Value)
- }
- if *subAgg.Value != float64(56.3) {
- t.Fatalf("expected sub-aggregation value = %v; got: %v", float64(56.3), *subAgg.Value)
- }
-}
-
-func TestAggsBucketFiltersWithBuckets(t *testing.T) {
- s := `{
- "messages" : {
- "buckets" : [
- {
- "doc_count" : 34,
- "monthly" : {
- "buckets" : []
- }
- },
- {
- "doc_count" : 439,
- "monthly" : {
- "buckets" : []
- }
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Filters("messages")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != %v; got: %v", nil, agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Fatalf("expected %d buckets; got: %d", 2, len(agg.Buckets))
- }
-
- if agg.Buckets[0].DocCount != 34 {
- t.Fatalf("expected DocCount = %d; got: %d", 34, agg.Buckets[0].DocCount)
- }
- subAgg, found := agg.Buckets[0].Histogram("monthly")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != %v; got: %v", nil, subAgg)
- }
-
- if agg.Buckets[1].DocCount != 439 {
- t.Fatalf("expected DocCount = %d; got: %d", 439, agg.Buckets[1].DocCount)
- }
- subAgg, found = agg.Buckets[1].Histogram("monthly")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != %v; got: %v", nil, subAgg)
- }
-}
-
-func TestAggsBucketFiltersWithNamedBuckets(t *testing.T) {
- s := `{
- "messages" : {
- "buckets" : {
- "errors" : {
- "doc_count" : 34,
- "monthly" : {
- "buckets" : []
- }
- },
- "warnings" : {
- "doc_count" : 439,
- "monthly" : {
- "buckets" : []
- }
- }
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Filters("messages")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.NamedBuckets == nil {
- t.Fatalf("expected aggregation buckets != %v; got: %v", nil, agg.NamedBuckets)
- }
- if len(agg.NamedBuckets) != 2 {
- t.Fatalf("expected %d buckets; got: %d", 2, len(agg.NamedBuckets))
- }
-
- if agg.NamedBuckets["errors"].DocCount != 34 {
- t.Fatalf("expected DocCount = %d; got: %d", 34, agg.NamedBuckets["errors"].DocCount)
- }
- subAgg, found := agg.NamedBuckets["errors"].Histogram("monthly")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != %v; got: %v", nil, subAgg)
- }
-
- if agg.NamedBuckets["warnings"].DocCount != 439 {
- t.Fatalf("expected DocCount = %d; got: %d", 439, agg.NamedBuckets["warnings"].DocCount)
- }
- subAgg, found = agg.NamedBuckets["warnings"].Histogram("monthly")
- if !found {
- t.Fatalf("expected sub aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub aggregation != %v; got: %v", nil, subAgg)
- }
-}
-
-func TestAggsBucketMissing(t *testing.T) {
- s := `{
- "products_without_a_price" : {
- "doc_count" : 10
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Missing("products_without_a_price")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 10 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 10, agg.DocCount)
- }
-}
-
-func TestAggsBucketNested(t *testing.T) {
- s := `{
- "resellers": {
- "min_price": {
- "value" : 350
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Nested("resellers")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 0 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 0, agg.DocCount)
- }
-
- // Sub-aggregation
- subAgg, found := agg.Avg("min_price")
- if !found {
- t.Fatalf("expected sub-aggregation to be found; got: %v", found)
- }
- if subAgg == nil {
- t.Fatalf("expected sub-aggregation != nil; got: %v", subAgg)
- }
- if subAgg.Value == nil {
- t.Fatalf("expected sub-aggregation value != nil; got: %v", subAgg.Value)
- }
- if *subAgg.Value != float64(350) {
- t.Fatalf("expected sub-aggregation value = %v; got: %v", float64(350), *subAgg.Value)
- }
-}
-
-func TestAggsBucketReverseNested(t *testing.T) {
- s := `{
- "comment_to_issue": {
- "doc_count" : 10
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.ReverseNested("comment_to_issue")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 10 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 10, agg.DocCount)
- }
-}
-
-func TestAggsBucketChildren(t *testing.T) {
- s := `{
- "to-answers": {
- "doc_count" : 10
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Children("to-answers")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 10 {
- t.Fatalf("expected aggregation DocCount = %d; got: %d", 10, agg.DocCount)
- }
-}
-
-func TestAggsBucketTerms(t *testing.T) {
- s := `{
- "users" : {
- "doc_count_error_upper_bound" : 1,
- "sum_other_doc_count" : 2,
- "buckets" : [ {
- "key" : "olivere",
- "doc_count" : 2
- }, {
- "key" : "sandrae",
- "doc_count" : 1
- } ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Terms("users")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != "olivere" {
- t.Errorf("expected key %q; got: %q", "olivere", agg.Buckets[0].Key)
- }
- if agg.Buckets[0].DocCount != 2 {
- t.Errorf("expected doc count %d; got: %d", 2, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != "sandrae" {
- t.Errorf("expected key %q; got: %q", "sandrae", agg.Buckets[1].Key)
- }
- if agg.Buckets[1].DocCount != 1 {
- t.Errorf("expected doc count %d; got: %d", 1, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketTermsWithNumericKeys(t *testing.T) {
- s := `{
- "users" : {
- "doc_count_error_upper_bound" : 1,
- "sum_other_doc_count" : 2,
- "buckets" : [ {
- "key" : 17,
- "doc_count" : 2
- }, {
- "key" : 21,
- "doc_count" : 1
- } ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Terms("users")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != float64(17) {
- t.Errorf("expected key %v; got: %v", 17, agg.Buckets[0].Key)
- }
- if got, err := agg.Buckets[0].KeyNumber.Int64(); err != nil {
- t.Errorf("expected to convert key to int64; got: %v", err)
- } else if got != 17 {
- t.Errorf("expected key %v; got: %v", 17, agg.Buckets[0].Key)
- }
- if agg.Buckets[0].DocCount != 2 {
- t.Errorf("expected doc count %d; got: %d", 2, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != float64(21) {
- t.Errorf("expected key %v; got: %v", 21, agg.Buckets[1].Key)
- }
- if got, err := agg.Buckets[1].KeyNumber.Int64(); err != nil {
- t.Errorf("expected to convert key to int64; got: %v", err)
- } else if got != 21 {
- t.Errorf("expected key %v; got: %v", 21, agg.Buckets[1].Key)
- }
- if agg.Buckets[1].DocCount != 1 {
- t.Errorf("expected doc count %d; got: %d", 1, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketTermsWithBoolKeys(t *testing.T) {
- s := `{
- "users" : {
- "doc_count_error_upper_bound" : 1,
- "sum_other_doc_count" : 2,
- "buckets" : [ {
- "key" : true,
- "doc_count" : 2
- }, {
- "key" : false,
- "doc_count" : 1
- } ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Terms("users")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != true {
- t.Errorf("expected key %v; got: %v", true, agg.Buckets[0].Key)
- }
- if agg.Buckets[0].DocCount != 2 {
- t.Errorf("expected doc count %d; got: %d", 2, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != false {
- t.Errorf("expected key %v; got: %v", false, agg.Buckets[1].Key)
- }
- if agg.Buckets[1].DocCount != 1 {
- t.Errorf("expected doc count %d; got: %d", 1, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketSignificantTerms(t *testing.T) {
- s := `{
- "significantCrimeTypes" : {
- "doc_count": 47347,
- "buckets" : [
- {
- "key": "Bicycle theft",
- "doc_count": 3640,
- "score": 0.371235374214817,
- "bg_count": 66799
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.SignificantTerms("significantCrimeTypes")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 47347 {
- t.Fatalf("expected aggregation DocCount != %d; got: %d", 47347, agg.DocCount)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 1 {
- t.Errorf("expected %d bucket entries; got: %d", 1, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != "Bicycle theft" {
- t.Errorf("expected key = %q; got: %q", "Bicycle theft", agg.Buckets[0].Key)
- }
- if agg.Buckets[0].DocCount != 3640 {
- t.Errorf("expected doc count = %d; got: %d", 3640, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[0].Score != float64(0.371235374214817) {
- t.Errorf("expected score = %v; got: %v", float64(0.371235374214817), agg.Buckets[0].Score)
- }
- if agg.Buckets[0].BgCount != 66799 {
- t.Errorf("expected BgCount = %d; got: %d", 66799, agg.Buckets[0].BgCount)
- }
-}
-
-func TestAggsBucketSampler(t *testing.T) {
- s := `{
- "sample" : {
- "doc_count": 1000,
- "keywords": {
- "doc_count": 1000,
- "buckets" : [
- {
- "key": "bend",
- "doc_count": 58,
- "score": 37.982536582524276,
- "bg_count": 103
- }
- ]
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Sampler("sample")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.DocCount != 1000 {
- t.Fatalf("expected aggregation DocCount != %d; got: %d", 1000, agg.DocCount)
- }
- sub, found := agg.Aggregations["keywords"]
- if !found {
- t.Fatalf("expected sub aggregation %q", "keywords")
- }
- if sub == nil {
- t.Fatalf("expected sub aggregation %q; got: %v", "keywords", sub)
- }
-}
-
-func TestAggsBucketRange(t *testing.T) {
- s := `{
- "price_ranges" : {
- "buckets": [
- {
- "to": 50,
- "doc_count": 2
- },
- {
- "from": 50,
- "to": 100,
- "doc_count": 4
- },
- {
- "from": 100,
- "doc_count": 4
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Range("price_ranges")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 3 {
- t.Errorf("expected %d bucket entries; got: %d", 3, len(agg.Buckets))
- }
- if agg.Buckets[0].From != nil {
- t.Errorf("expected From = %v; got: %v", nil, agg.Buckets[0].From)
- }
- if agg.Buckets[0].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[0].To)
- }
- if *agg.Buckets[0].To != float64(50) {
- t.Errorf("expected To = %v; got: %v", float64(50), *agg.Buckets[0].To)
- }
- if agg.Buckets[0].DocCount != 2 {
- t.Errorf("expected DocCount = %d; got: %d", 2, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[1].From)
- }
- if *agg.Buckets[1].From != float64(50) {
- t.Errorf("expected From = %v; got: %v", float64(50), *agg.Buckets[1].From)
- }
- if agg.Buckets[1].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[1].To)
- }
- if *agg.Buckets[1].To != float64(100) {
- t.Errorf("expected To = %v; got: %v", float64(100), *agg.Buckets[1].To)
- }
- if agg.Buckets[1].DocCount != 4 {
- t.Errorf("expected DocCount = %d; got: %d", 4, agg.Buckets[1].DocCount)
- }
- if agg.Buckets[2].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[2].From)
- }
- if *agg.Buckets[2].From != float64(100) {
- t.Errorf("expected From = %v; got: %v", float64(100), *agg.Buckets[2].From)
- }
- if agg.Buckets[2].To != nil {
- t.Errorf("expected To = %v; got: %v", nil, agg.Buckets[2].To)
- }
- if agg.Buckets[2].DocCount != 4 {
- t.Errorf("expected DocCount = %d; got: %d", 4, agg.Buckets[2].DocCount)
- }
-}
-
-func TestAggsBucketDateRange(t *testing.T) {
- s := `{
- "range": {
- "buckets": [
- {
- "to": 1.3437792E+12,
- "to_as_string": "08-2012",
- "doc_count": 7
- },
- {
- "from": 1.3437792E+12,
- "from_as_string": "08-2012",
- "doc_count": 2
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.DateRange("range")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].From != nil {
- t.Errorf("expected From = %v; got: %v", nil, agg.Buckets[0].From)
- }
- if agg.Buckets[0].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[0].To)
- }
- if *agg.Buckets[0].To != float64(1.3437792E+12) {
- t.Errorf("expected To = %v; got: %v", float64(1.3437792E+12), *agg.Buckets[0].To)
- }
- if agg.Buckets[0].ToAsString != "08-2012" {
- t.Errorf("expected ToAsString = %q; got: %q", "08-2012", agg.Buckets[0].ToAsString)
- }
- if agg.Buckets[0].DocCount != 7 {
- t.Errorf("expected DocCount = %d; got: %d", 7, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[1].From)
- }
- if *agg.Buckets[1].From != float64(1.3437792E+12) {
- t.Errorf("expected From = %v; got: %v", float64(1.3437792E+12), *agg.Buckets[1].From)
- }
- if agg.Buckets[1].FromAsString != "08-2012" {
- t.Errorf("expected FromAsString = %q; got: %q", "08-2012", agg.Buckets[1].FromAsString)
- }
- if agg.Buckets[1].To != nil {
- t.Errorf("expected To = %v; got: %v", nil, agg.Buckets[1].To)
- }
- if agg.Buckets[1].DocCount != 2 {
- t.Errorf("expected DocCount = %d; got: %d", 2, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketIPRange(t *testing.T) {
- s := `{
- "ip_ranges": {
- "buckets" : [
- {
- "to": 167772165,
- "to_as_string": "10.0.0.5",
- "doc_count": 4
- },
- {
- "from": 167772165,
- "from_as_string": "10.0.0.5",
- "doc_count": 6
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.IPRange("ip_ranges")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].From != nil {
- t.Errorf("expected From = %v; got: %v", nil, agg.Buckets[0].From)
- }
- if agg.Buckets[0].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[0].To)
- }
- if *agg.Buckets[0].To != float64(167772165) {
- t.Errorf("expected To = %v; got: %v", float64(167772165), *agg.Buckets[0].To)
- }
- if agg.Buckets[0].ToAsString != "10.0.0.5" {
- t.Errorf("expected ToAsString = %q; got: %q", "10.0.0.5", agg.Buckets[0].ToAsString)
- }
- if agg.Buckets[0].DocCount != 4 {
- t.Errorf("expected DocCount = %d; got: %d", 4, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[1].From)
- }
- if *agg.Buckets[1].From != float64(167772165) {
- t.Errorf("expected From = %v; got: %v", float64(167772165), *agg.Buckets[1].From)
- }
- if agg.Buckets[1].FromAsString != "10.0.0.5" {
- t.Errorf("expected FromAsString = %q; got: %q", "10.0.0.5", agg.Buckets[1].FromAsString)
- }
- if agg.Buckets[1].To != nil {
- t.Errorf("expected To = %v; got: %v", nil, agg.Buckets[1].To)
- }
- if agg.Buckets[1].DocCount != 6 {
- t.Errorf("expected DocCount = %d; got: %d", 6, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketHistogram(t *testing.T) {
- s := `{
- "prices" : {
- "buckets": [
- {
- "key": 0,
- "doc_count": 2
- },
- {
- "key": 50,
- "doc_count": 4
- },
- {
- "key": 150,
- "doc_count": 3
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Histogram("prices")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 3 {
- t.Errorf("expected %d buckets; got: %d", 3, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != 0 {
- t.Errorf("expected key = %v; got: %v", 0, agg.Buckets[0].Key)
- }
- if agg.Buckets[0].KeyAsString != nil {
- t.Fatalf("expected key_as_string = %v; got: %q", nil, *agg.Buckets[0].KeyAsString)
- }
- if agg.Buckets[0].DocCount != 2 {
- t.Errorf("expected doc count = %d; got: %d", 2, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != 50 {
- t.Errorf("expected key = %v; got: %v", 50, agg.Buckets[1].Key)
- }
- if agg.Buckets[1].KeyAsString != nil {
- t.Fatalf("expected key_as_string = %v; got: %q", nil, *agg.Buckets[1].KeyAsString)
- }
- if agg.Buckets[1].DocCount != 4 {
- t.Errorf("expected doc count = %d; got: %d", 4, agg.Buckets[1].DocCount)
- }
- if agg.Buckets[2].Key != 150 {
- t.Errorf("expected key = %v; got: %v", 150, agg.Buckets[2].Key)
- }
- if agg.Buckets[2].KeyAsString != nil {
- t.Fatalf("expected key_as_string = %v; got: %q", nil, *agg.Buckets[2].KeyAsString)
- }
- if agg.Buckets[2].DocCount != 3 {
- t.Errorf("expected doc count = %d; got: %d", 3, agg.Buckets[2].DocCount)
- }
-}
-
-func TestAggsBucketDateHistogram(t *testing.T) {
- s := `{
- "articles_over_time": {
- "buckets": [
- {
- "key_as_string": "2013-02-02",
- "key": 1328140800000,
- "doc_count": 1
- },
- {
- "key_as_string": "2013-03-02",
- "key": 1330646400000,
- "doc_count": 2
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.DateHistogram("articles_over_time")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != 1328140800000 {
- t.Errorf("expected key %v; got: %v", 1328140800000, agg.Buckets[0].Key)
- }
- if agg.Buckets[0].KeyAsString == nil {
- t.Fatalf("expected key_as_string != nil; got: %v", agg.Buckets[0].KeyAsString)
- }
- if *agg.Buckets[0].KeyAsString != "2013-02-02" {
- t.Errorf("expected key_as_string %q; got: %q", "2013-02-02", *agg.Buckets[0].KeyAsString)
- }
- if agg.Buckets[0].DocCount != 1 {
- t.Errorf("expected doc count %d; got: %d", 1, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != 1330646400000 {
- t.Errorf("expected key %v; got: %v", 1330646400000, agg.Buckets[1].Key)
- }
- if agg.Buckets[1].KeyAsString == nil {
- t.Fatalf("expected key_as_string != nil; got: %v", agg.Buckets[1].KeyAsString)
- }
- if *agg.Buckets[1].KeyAsString != "2013-03-02" {
- t.Errorf("expected key_as_string %q; got: %q", "2013-03-02", *agg.Buckets[1].KeyAsString)
- }
- if agg.Buckets[1].DocCount != 2 {
- t.Errorf("expected doc count %d; got: %d", 2, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsMetricsGeoBounds(t *testing.T) {
- s := `{
- "viewport": {
- "bounds": {
- "top_left": {
- "lat": 80.45,
- "lon": -160.22
- },
- "bottom_right": {
- "lat": 40.65,
- "lon": 42.57
- }
- }
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.GeoBounds("viewport")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Bounds.TopLeft.Latitude != float64(80.45) {
- t.Fatalf("expected Bounds.TopLeft.Latitude != %v; got: %v", float64(80.45), agg.Bounds.TopLeft.Latitude)
- }
- if agg.Bounds.TopLeft.Longitude != float64(-160.22) {
- t.Fatalf("expected Bounds.TopLeft.Longitude != %v; got: %v", float64(-160.22), agg.Bounds.TopLeft.Longitude)
- }
- if agg.Bounds.BottomRight.Latitude != float64(40.65) {
- t.Fatalf("expected Bounds.BottomRight.Latitude != %v; got: %v", float64(40.65), agg.Bounds.BottomRight.Latitude)
- }
- if agg.Bounds.BottomRight.Longitude != float64(42.57) {
- t.Fatalf("expected Bounds.BottomRight.Longitude != %v; got: %v", float64(42.57), agg.Bounds.BottomRight.Longitude)
- }
-}
-
-func TestAggsBucketGeoHash(t *testing.T) {
- s := `{
- "myLarge-GrainGeoHashGrid": {
- "buckets": [
- {
- "key": "svz",
- "doc_count": 10964
- },
- {
- "key": "sv8",
- "doc_count": 3198
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.GeoHash("myLarge-GrainGeoHashGrid")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(agg.Buckets))
- }
- if agg.Buckets[0].Key != "svz" {
- t.Errorf("expected key %q; got: %q", "svz", agg.Buckets[0].Key)
- }
- if agg.Buckets[0].DocCount != 10964 {
- t.Errorf("expected doc count %d; got: %d", 10964, agg.Buckets[0].DocCount)
- }
- if agg.Buckets[1].Key != "sv8" {
- t.Errorf("expected key %q; got: %q", "sv8", agg.Buckets[1].Key)
- }
- if agg.Buckets[1].DocCount != 3198 {
- t.Errorf("expected doc count %d; got: %d", 3198, agg.Buckets[1].DocCount)
- }
-}
-
-func TestAggsBucketGeoDistance(t *testing.T) {
- s := `{
- "rings" : {
- "buckets": [
- {
- "unit": "km",
- "to": 100.0,
- "doc_count": 3
- },
- {
- "unit": "km",
- "from": 100.0,
- "to": 300.0,
- "doc_count": 1
- },
- {
- "unit": "km",
- "from": 300.0,
- "doc_count": 7
- }
- ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.GeoDistance("rings")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Buckets == nil {
- t.Fatalf("expected aggregation buckets != nil; got: %v", agg.Buckets)
- }
- if len(agg.Buckets) != 3 {
- t.Errorf("expected %d bucket entries; got: %d", 3, len(agg.Buckets))
- }
- if agg.Buckets[0].From != nil {
- t.Errorf("expected From = %v; got: %v", nil, agg.Buckets[0].From)
- }
- if agg.Buckets[0].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[0].To)
- }
- if *agg.Buckets[0].To != float64(100.0) {
- t.Errorf("expected To = %v; got: %v", float64(100.0), *agg.Buckets[0].To)
- }
- if agg.Buckets[0].DocCount != 3 {
- t.Errorf("expected DocCount = %d; got: %d", 4, agg.Buckets[0].DocCount)
- }
-
- if agg.Buckets[1].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[1].From)
- }
- if *agg.Buckets[1].From != float64(100.0) {
- t.Errorf("expected From = %v; got: %v", float64(100.0), *agg.Buckets[1].From)
- }
- if agg.Buckets[1].To == nil {
- t.Errorf("expected To != %v; got: %v", nil, agg.Buckets[1].To)
- }
- if *agg.Buckets[1].To != float64(300.0) {
- t.Errorf("expected From = %v; got: %v", float64(300.0), *agg.Buckets[1].To)
- }
- if agg.Buckets[1].DocCount != 1 {
- t.Errorf("expected DocCount = %d; got: %d", 1, agg.Buckets[1].DocCount)
- }
-
- if agg.Buckets[2].From == nil {
- t.Errorf("expected From != %v; got: %v", nil, agg.Buckets[2].From)
- }
- if *agg.Buckets[2].From != float64(300.0) {
- t.Errorf("expected From = %v; got: %v", float64(300.0), *agg.Buckets[2].From)
- }
- if agg.Buckets[2].To != nil {
- t.Errorf("expected To = %v; got: %v", nil, agg.Buckets[2].To)
- }
- if agg.Buckets[2].DocCount != 7 {
- t.Errorf("expected DocCount = %d; got: %d", 7, agg.Buckets[2].DocCount)
- }
-}
-
-func TestAggsSubAggregates(t *testing.T) {
- rs := `{
- "users" : {
- "doc_count_error_upper_bound" : 1,
- "sum_other_doc_count" : 2,
- "buckets" : [ {
- "key" : "olivere",
- "doc_count" : 2,
- "ts" : {
- "buckets" : [ {
- "key_as_string" : "2012-01-01T00:00:00.000Z",
- "key" : 1325376000000,
- "doc_count" : 2
- } ]
- }
- }, {
- "key" : "sandrae",
- "doc_count" : 1,
- "ts" : {
- "buckets" : [ {
- "key_as_string" : "2011-01-01T00:00:00.000Z",
- "key" : 1293840000000,
- "doc_count" : 1
- } ]
- }
- } ]
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(rs), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- // Access top-level aggregation
- users, found := aggs.Terms("users")
- if !found {
- t.Fatalf("expected users aggregation to be found; got: %v", found)
- }
- if users == nil {
- t.Fatalf("expected users aggregation; got: %v", users)
- }
- if users.Buckets == nil {
- t.Fatalf("expected users buckets; got: %v", users.Buckets)
- }
- if len(users.Buckets) != 2 {
- t.Errorf("expected %d bucket entries; got: %d", 2, len(users.Buckets))
- }
- if users.Buckets[0].Key != "olivere" {
- t.Errorf("expected key %q; got: %q", "olivere", users.Buckets[0].Key)
- }
- if users.Buckets[0].DocCount != 2 {
- t.Errorf("expected doc count %d; got: %d", 2, users.Buckets[0].DocCount)
- }
- if users.Buckets[1].Key != "sandrae" {
- t.Errorf("expected key %q; got: %q", "sandrae", users.Buckets[1].Key)
- }
- if users.Buckets[1].DocCount != 1 {
- t.Errorf("expected doc count %d; got: %d", 1, users.Buckets[1].DocCount)
- }
-
- // Access sub-aggregation
- ts, found := users.Buckets[0].DateHistogram("ts")
- if !found {
- t.Fatalf("expected ts aggregation to be found; got: %v", found)
- }
- if ts == nil {
- t.Fatalf("expected ts aggregation; got: %v", ts)
- }
- if ts.Buckets == nil {
- t.Fatalf("expected ts buckets; got: %v", ts.Buckets)
- }
- if len(ts.Buckets) != 1 {
- t.Errorf("expected %d bucket entries; got: %d", 1, len(ts.Buckets))
- }
- if ts.Buckets[0].Key != 1325376000000 {
- t.Errorf("expected key %v; got: %v", 1325376000000, ts.Buckets[0].Key)
- }
- if ts.Buckets[0].KeyAsString == nil {
- t.Fatalf("expected key_as_string != %v; got: %v", nil, ts.Buckets[0].KeyAsString)
- }
- if *ts.Buckets[0].KeyAsString != "2012-01-01T00:00:00.000Z" {
- t.Errorf("expected key_as_string %q; got: %q", "2012-01-01T00:00:00.000Z", *ts.Buckets[0].KeyAsString)
- }
-}
-
-func TestAggsPipelineAvgBucket(t *testing.T) {
- s := `{
- "avg_monthly_sales" : {
- "value" : 328.33333333333333
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.AvgBucket("avg_monthly_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(328.33333333333333) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(328.33333333333333), *agg.Value)
- }
-}
-
-func TestAggsPipelineSumBucket(t *testing.T) {
- s := `{
- "sum_monthly_sales" : {
- "value" : 985
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.SumBucket("sum_monthly_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(985) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(985), *agg.Value)
- }
-}
-
-func TestAggsPipelineMaxBucket(t *testing.T) {
- s := `{
- "max_monthly_sales" : {
- "keys": ["2015/01/01 00:00:00"],
- "value" : 550
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.MaxBucket("max_monthly_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if len(agg.Keys) != 1 {
- t.Fatalf("expected 1 key; got: %d", len(agg.Keys))
- }
- if got, want := agg.Keys[0], "2015/01/01 00:00:00"; got != want {
- t.Fatalf("expected key %q; got: %v (%T)", want, got, got)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(550) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(550), *agg.Value)
- }
-}
-
-func TestAggsPipelineMinBucket(t *testing.T) {
- s := `{
- "min_monthly_sales" : {
- "keys": ["2015/02/01 00:00:00"],
- "value" : 60
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.MinBucket("min_monthly_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if len(agg.Keys) != 1 {
- t.Fatalf("expected 1 key; got: %d", len(agg.Keys))
- }
- if got, want := agg.Keys[0], "2015/02/01 00:00:00"; got != want {
- t.Fatalf("expected key %q; got: %v (%T)", want, got, got)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(60) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(60), *agg.Value)
- }
-}
-
-func TestAggsPipelineMovAvg(t *testing.T) {
- s := `{
- "the_movavg" : {
- "value" : 12.0
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.MovAvg("the_movavg")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(12.0) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(12.0), *agg.Value)
- }
-}
-
-func TestAggsPipelineDerivative(t *testing.T) {
- s := `{
- "sales_deriv" : {
- "value" : 315
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Derivative("sales_deriv")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(315) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(315), *agg.Value)
- }
-}
-
-func TestAggsPipelinePercentilesBucket(t *testing.T) {
- s := `{
- "sales_percentiles": {
- "values": {
- "25.0": 100,
- "50.0": 200,
- "75.0": 300
- }
- }
-}`
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.PercentilesBucket("sales_percentiles")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if len(agg.Values) != 3 {
- t.Fatalf("expected aggregation map with three entries; got: %v", agg.Values)
- }
-}
-
-func TestAggsPipelineStatsBucket(t *testing.T) {
- s := `{
- "stats_monthly_sales": {
- "count": 3,
- "min": 60.0,
- "max": 550.0,
- "avg": 328.3333333333333,
- "sum": 985.0
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.StatsBucket("stats_monthly_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Count != 3 {
- t.Fatalf("expected aggregation count = %v; got: %v", 3, agg.Count)
- }
- if agg.Min == nil {
- t.Fatalf("expected aggregation min != nil; got: %v", agg.Min)
- }
- if *agg.Min != float64(60.0) {
- t.Fatalf("expected aggregation min = %v; got: %v", float64(60.0), *agg.Min)
- }
- if agg.Max == nil {
- t.Fatalf("expected aggregation max != nil; got: %v", agg.Max)
- }
- if *agg.Max != float64(550.0) {
- t.Fatalf("expected aggregation max = %v; got: %v", float64(550.0), *agg.Max)
- }
- if agg.Avg == nil {
- t.Fatalf("expected aggregation avg != nil; got: %v", agg.Avg)
- }
- if *agg.Avg != float64(328.3333333333333) {
- t.Fatalf("expected aggregation average = %v; got: %v", float64(328.3333333333333), *agg.Avg)
- }
- if agg.Sum == nil {
- t.Fatalf("expected aggregation sum != nil; got: %v", agg.Sum)
- }
- if *agg.Sum != float64(985.0) {
- t.Fatalf("expected aggregation sum = %v; got: %v", float64(985.0), *agg.Sum)
- }
-}
-
-func TestAggsPipelineCumulativeSum(t *testing.T) {
- s := `{
- "cumulative_sales" : {
- "value" : 550
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.CumulativeSum("cumulative_sales")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(550) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(550), *agg.Value)
- }
-}
-
-func TestAggsPipelineBucketScript(t *testing.T) {
- s := `{
- "t-shirt-percentage" : {
- "value" : 20
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.BucketScript("t-shirt-percentage")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(20) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(20), *agg.Value)
- }
-}
-
-func TestAggsPipelineSerialDiff(t *testing.T) {
- s := `{
- "the_diff" : {
- "value" : -722.0
- }
-}`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.SerialDiff("the_diff")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if agg.Value == nil {
- t.Fatalf("expected aggregation value != nil; got: %v", agg.Value)
- }
- if *agg.Value != float64(-722.0) {
- t.Fatalf("expected aggregation value = %v; got: %v", float64(20), *agg.Value)
- }
-}
-
-func TestAggsComposite(t *testing.T) {
- s := `{
- "the_composite" : {
- "buckets" : [
- {
- "key" : {
- "composite_users" : "olivere",
- "composite_retweets" : 0.0,
- "composite_created" : 1349856720000
- },
- "doc_count" : 1
- },
- {
- "key" : {
- "composite_users" : "olivere",
- "composite_retweets" : 108.0,
- "composite_created" : 1355333880000
- },
- "doc_count" : 1
- },
- {
- "key" : {
- "composite_users" : "sandrae",
- "composite_retweets" : 12.0,
- "composite_created" : 1321009080000
- },
- "doc_count" : 1
- }
- ]
- }
- }`
-
- aggs := new(Aggregations)
- err := json.Unmarshal([]byte(s), &aggs)
- if err != nil {
- t.Fatalf("expected no error decoding; got: %v", err)
- }
-
- agg, found := aggs.Composite("the_composite")
- if !found {
- t.Fatalf("expected aggregation to be found; got: %v", found)
- }
- if agg == nil {
- t.Fatalf("expected aggregation != nil; got: %v", agg)
- }
- if want, have := 3, len(agg.Buckets); want != have {
- t.Fatalf("expected aggregation buckets length = %v; got: %v", want, have)
- }
-
- // 1st bucket
- bucket := agg.Buckets[0]
- if want, have := int64(1), bucket.DocCount; want != have {
- t.Fatalf("expected aggregation bucket doc count = %v; got: %v", want, have)
- }
- if want, have := 3, len(bucket.Key); want != have {
- t.Fatalf("expected aggregation bucket key length = %v; got: %v", want, have)
- }
- v, found := bucket.Key["composite_users"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_users")
- }
- s, ok := v.(string)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := "olivere", s; want != have {
- t.Fatalf("expected to find bucket key value %q; got: %q", want, have)
- }
- v, found = bucket.Key["composite_retweets"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_retweets")
- }
- f, ok := v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 0.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
- v, found = bucket.Key["composite_created"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_created")
- }
- f, ok = v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 1349856720000.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
-
- // 2nd bucket
- bucket = agg.Buckets[1]
- if want, have := int64(1), bucket.DocCount; want != have {
- t.Fatalf("expected aggregation bucket doc count = %v; got: %v", want, have)
- }
- if want, have := 3, len(bucket.Key); want != have {
- t.Fatalf("expected aggregation bucket key length = %v; got: %v", want, have)
- }
- v, found = bucket.Key["composite_users"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_users")
- }
- s, ok = v.(string)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := "olivere", s; want != have {
- t.Fatalf("expected to find bucket key value %q; got: %q", want, have)
- }
- v, found = bucket.Key["composite_retweets"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_retweets")
- }
- f, ok = v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 108.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
- v, found = bucket.Key["composite_created"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_created")
- }
- f, ok = v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 1355333880000.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
-
- // 3rd bucket
- bucket = agg.Buckets[2]
- if want, have := int64(1), bucket.DocCount; want != have {
- t.Fatalf("expected aggregation bucket doc count = %v; got: %v", want, have)
- }
- if want, have := 3, len(bucket.Key); want != have {
- t.Fatalf("expected aggregation bucket key length = %v; got: %v", want, have)
- }
- v, found = bucket.Key["composite_users"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_users")
- }
- s, ok = v.(string)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := "sandrae", s; want != have {
- t.Fatalf("expected to find bucket key value %q; got: %q", want, have)
- }
- v, found = bucket.Key["composite_retweets"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_retweets")
- }
- f, ok = v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 12.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
- v, found = bucket.Key["composite_created"]
- if !found {
- t.Fatalf("expected to find bucket key %q", "composite_created")
- }
- f, ok = v.(float64)
- if !ok {
- t.Fatalf("expected to have bucket key of type string; got: %T", v)
- }
- if want, have := 1321009080000.0, f; want != have {
- t.Fatalf("expected to find bucket key value %v; got: %v", want, have)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder.go b/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder.go
index b3c628ba3..48ed17acb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder.go
@@ -5,7 +5,7 @@
package elastic
// CollapseBuilder enables field collapsing on a search request.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-collapse.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-request-collapse.html
// for details.
type CollapseBuilder struct {
field string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder_test.go
deleted file mode 100644
index 0b74fadab..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_collapse_builder_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestCollapseBuilderSource(t *testing.T) {
- b := NewCollapseBuilder("user").
- InnerHit(NewInnerHit().Name("last_tweets").Size(5).Sort("date", true)).
- MaxConcurrentGroupRequests(4)
- src, err := b.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"field":"user","inner_hits":{"name":"last_tweets","size":5,"sort":[{"date":{"order":"asc"}}]},"max_concurrent_group_searches":4}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool.go
index a1ff17596..8ae223834 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool.go
@@ -9,7 +9,7 @@ import "fmt"
// A bool query matches documents matching boolean
// combinations of other queries.
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-bool-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-bool-query.html
type BoolQuery struct {
Query
mustClauses []Query
@@ -17,6 +17,7 @@ type BoolQuery struct {
filterClauses []Query
shouldClauses []Query
boost *float64
+ disableCoord *bool
minimumShouldMatch string
adjustPureNegative *bool
queryName string
@@ -57,6 +58,11 @@ func (q *BoolQuery) Boost(boost float64) *BoolQuery {
return q
}
+func (q *BoolQuery) DisableCoord(disableCoord bool) *BoolQuery {
+ q.disableCoord = &disableCoord
+ return q
+}
+
func (q *BoolQuery) MinimumShouldMatch(minimumShouldMatch string) *BoolQuery {
q.minimumShouldMatch = minimumShouldMatch
return q
@@ -100,7 +106,7 @@ func (q *BoolQuery) Source() (interface{}, error) {
// "term" : { "tag" : "elasticsearch" }
// }
// ],
- // "minimum_should_match" : 1,
+ // "minimum_number_should_match" : 1,
// "boost" : 1.0
// }
// }
@@ -189,6 +195,9 @@ func (q *BoolQuery) Source() (interface{}, error) {
if q.boost != nil {
boolClause["boost"] = *q.boost
}
+ if q.disableCoord != nil {
+ boolClause["disable_coord"] = *q.disableCoord
+ }
if q.minimumShouldMatch != "" {
boolClause["minimum_should_match"] = q.minimumShouldMatch
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool_test.go
deleted file mode 100644
index cdcc38de1..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_bool_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestBoolQuery(t *testing.T) {
- q := NewBoolQuery()
- q = q.Must(NewTermQuery("tag", "wow"))
- q = q.MustNot(NewRangeQuery("age").From(10).To(20))
- q = q.Filter(NewTermQuery("account", "1"))
- q = q.Should(NewTermQuery("tag", "sometag"), NewTermQuery("tag", "sometagtag"))
- q = q.Boost(10)
- q = q.QueryName("Test")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"bool":{"_name":"Test","boost":10,"filter":{"term":{"account":"1"}},"must":{"term":{"tag":"wow"}},"must_not":{"range":{"age":{"from":10,"include_lower":true,"include_upper":true,"to":20}}},"should":[{"term":{"tag":"sometag"}},{"term":{"tag":"sometagtag"}}]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting.go
index 0060a30a8..3a31237c9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting.go
@@ -7,7 +7,7 @@ package elastic
// A boosting query can be used to effectively
// demote results that match a given query.
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-boosting-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-boosting-query.html
type BoostingQuery struct {
Query
positiveClause Query
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting_test.go
deleted file mode 100644
index 6c7f263f4..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_boosting_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestBoostingQuery(t *testing.T) {
- q := NewBoostingQuery()
- q = q.Positive(NewTermQuery("tag", "wow"))
- q = q.Negative(NewRangeQuery("age").From(10).To(20))
- q = q.NegativeBoost(0.2)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"boosting":{"negative":{"range":{"age":{"from":10,"include_lower":true,"include_upper":true,"to":20}}},"negative_boost":0.2,"positive":{"term":{"tag":"wow"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms.go
index 93a03de54..a1a37b37c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms.go
@@ -8,7 +8,7 @@ package elastic
// which improves the precision and recall of search results
// (by taking stopwords into account), without sacrificing performance.
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-common-terms-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-common-terms-query.html
type CommonTermsQuery struct {
Query
name string
@@ -22,6 +22,7 @@ type CommonTermsQuery struct {
lowFreqMinimumShouldMatch string
analyzer string
boost *float64
+ disableCoord *bool
queryName string
}
@@ -75,6 +76,11 @@ func (q *CommonTermsQuery) Boost(boost float64) *CommonTermsQuery {
return q
}
+func (q *CommonTermsQuery) DisableCoord(disableCoord bool) *CommonTermsQuery {
+ q.disableCoord = &disableCoord
+ return q
+}
+
func (q *CommonTermsQuery) QueryName(queryName string) *CommonTermsQuery {
q.queryName = queryName
return q
@@ -126,6 +132,9 @@ func (q *CommonTermsQuery) Source() (interface{}, error) {
if q.analyzer != "" {
query["analyzer"] = q.analyzer
}
+ if q.disableCoord != nil {
+ query["disable_coord"] = *q.disableCoord
+ }
if q.boost != nil {
query["boost"] = *q.boost
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms_test.go
deleted file mode 100644
index e841e7731..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_common_terms_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- _ "net/http"
- "testing"
-)
-
-func TestCommonTermsQuery(t *testing.T) {
- q := NewCommonTermsQuery("message", "Golang").CutoffFrequency(0.001)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"common":{"message":{"cutoff_frequency":0.001,"query":"Golang"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchQueriesCommonTermsQuery(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Common terms query
- q := NewCommonTermsQuery("message", "Golang")
- searchResult, err := client.Search().Index(testIndexName).Query(q).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 1 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 1 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 1, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score.go
index 285d91817..3ba879958 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score.go
@@ -8,7 +8,7 @@ package elastic
// a constant score equal to the query boost for every document in the filter.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-constant-score-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-constant-score-query.html
type ConstantScoreQuery struct {
filter Query
boost *float64
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score_test.go
deleted file mode 100644
index 6508a91fb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_constant_score_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestConstantScoreQuery(t *testing.T) {
- q := NewConstantScoreQuery(NewTermQuery("user", "kimchy")).Boost(1.2)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"constant_score":{"boost":1.2,"filter":{"term":{"user":"kimchy"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max.go
index 7a4f53a97..af9a40d37 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max.go
@@ -10,7 +10,7 @@ package elastic
// increment for any additional matching subqueries.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-dis-max-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-dis-max-query.html
type DisMaxQuery struct {
queries []Query
boost *float64
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max_test.go
deleted file mode 100644
index 76ddfb079..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_dis_max_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestDisMaxQuery(t *testing.T) {
- q := NewDisMaxQuery()
- q = q.Query(NewTermQuery("age", 34), NewTermQuery("age", 35)).Boost(1.2).TieBreaker(0.7)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"dis_max":{"boost":1.2,"queries":[{"term":{"age":34}},{"term":{"age":35}}],"tie_breaker":0.7}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists.go
index ac7378bad..6c2ebd369 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists.go
@@ -8,7 +8,7 @@ package elastic
// has a value in them.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-exists-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-exists-query.html
type ExistsQuery struct {
name string
queryName string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists_test.go
deleted file mode 100644
index f2d047087..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_exists_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestExistsQuery(t *testing.T) {
- q := NewExistsQuery("user")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"exists":{"field":"user"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq.go
index 4cabd9bd9..ec34302f8 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq.go
@@ -10,7 +10,7 @@ package elastic
// to compute the score on a filtered set of documents.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html
type FunctionScoreQuery struct {
query Query
filter Query
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_score_funcs.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_score_funcs.go
index 84cc52de9..622b645bb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_score_funcs.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_score_funcs.go
@@ -18,7 +18,7 @@ type ScoreFunction interface {
// -- Exponential Decay --
// ExponentialDecayFunction builds an exponential decay score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html
// for details.
type ExponentialDecayFunction struct {
fieldName string
@@ -75,7 +75,7 @@ func (fn *ExponentialDecayFunction) Offset(offset interface{}) *ExponentialDecay
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *ExponentialDecayFunction) Weight(weight float64) *ExponentialDecayFunction {
fn.weight = &weight
@@ -120,7 +120,7 @@ func (fn *ExponentialDecayFunction) Source() (interface{}, error) {
// -- Gauss Decay --
// GaussDecayFunction builds a gauss decay score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html
// for details.
type GaussDecayFunction struct {
fieldName string
@@ -177,7 +177,7 @@ func (fn *GaussDecayFunction) Offset(offset interface{}) *GaussDecayFunction {
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *GaussDecayFunction) Weight(weight float64) *GaussDecayFunction {
fn.weight = &weight
@@ -223,7 +223,7 @@ func (fn *GaussDecayFunction) Source() (interface{}, error) {
// -- Linear Decay --
// LinearDecayFunction builds a linear decay score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html
// for details.
type LinearDecayFunction struct {
fieldName string
@@ -280,7 +280,7 @@ func (fn *LinearDecayFunction) Offset(offset interface{}) *LinearDecayFunction {
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *LinearDecayFunction) Weight(weight float64) *LinearDecayFunction {
fn.weight = &weight
@@ -336,7 +336,7 @@ func (fn *LinearDecayFunction) Source() (interface{}, error) {
// compute or influence the score of documents that match with the inner
// query or filter.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_script_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_script_score
// for details.
type ScriptFunction struct {
script *Script
@@ -363,7 +363,7 @@ func (fn *ScriptFunction) Script(script *Script) *ScriptFunction {
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *ScriptFunction) Weight(weight float64) *ScriptFunction {
fn.weight = &weight
@@ -394,7 +394,7 @@ func (fn *ScriptFunction) Source() (interface{}, error) {
// FieldValueFactorFunction is a function score function that allows you
// to use a field from a document to influence the score.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_field_value_factor.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_field_value_factor.
type FieldValueFactorFunction struct {
field string
factor *float64
@@ -435,7 +435,7 @@ func (fn *FieldValueFactorFunction) Modifier(modifier string) *FieldValueFactorF
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *FieldValueFactorFunction) Weight(weight float64) *FieldValueFactorFunction {
fn.weight = &weight
@@ -477,7 +477,7 @@ func (fn *FieldValueFactorFunction) Source() (interface{}, error) {
// WeightFactorFunction builds a weight factor function that multiplies
// the weight to the score.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_weight
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_weight
// for details.
type WeightFactorFunction struct {
weight float64
@@ -495,7 +495,7 @@ func (fn *WeightFactorFunction) Name() string {
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *WeightFactorFunction) Weight(weight float64) *WeightFactorFunction {
fn.weight = weight
@@ -517,7 +517,7 @@ func (fn *WeightFactorFunction) Source() (interface{}, error) {
// -- Random --
// RandomFunction builds a random score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_random
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_random
// for details.
type RandomFunction struct {
seed interface{}
@@ -543,7 +543,7 @@ func (fn *RandomFunction) Seed(seed interface{}) *RandomFunction {
}
// Weight adjusts the score of the score function.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-function-score-query.html#_using_function_score
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-function-score-query.html#_using_function_score
// for details.
func (fn *RandomFunction) Weight(weight float64) *RandomFunction {
fn.weight = &weight
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_test.go
deleted file mode 100644
index 256752d18..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fsq_test.go
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestFunctionScoreQuery(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- Add(NewTermQuery("name.last", "banon"), NewWeightFactorFunction(1.5)).
- AddScoreFunc(NewWeightFactorFunction(3)).
- AddScoreFunc(NewRandomFunction()).
- Boost(3).
- MaxBoost(10).
- ScoreMode("avg")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"boost":3,"functions":[{"filter":{"term":{"name.last":"banon"}},"weight":1.5},{"weight":3},{"random_score":{}}],"max_boost":10,"query":{"term":{"name.last":"banon"}},"score_mode":"avg"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFunctionScoreQueryWithNilFilter(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("tag", "wow")).
- AddScoreFunc(NewRandomFunction()).
- Boost(2.0).
- MaxBoost(12.0).
- BoostMode("multiply").
- ScoreMode("max")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"boost":2,"boost_mode":"multiply","max_boost":12,"query":{"term":{"tag":"wow"}},"random_score":{},"score_mode":"max"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldValueFactor(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- AddScoreFunc(NewFieldValueFactorFunction().Modifier("sqrt").Factor(2).Field("income")).
- Boost(2.0).
- MaxBoost(12.0).
- BoostMode("multiply").
- ScoreMode("max")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"boost":2,"boost_mode":"multiply","field_value_factor":{"factor":2,"field":"income","modifier":"sqrt"},"max_boost":12,"query":{"term":{"name.last":"banon"}},"score_mode":"max"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldValueFactorWithWeight(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- AddScoreFunc(NewFieldValueFactorFunction().Modifier("sqrt").Factor(2).Field("income").Weight(2.5)).
- Boost(2.0).
- MaxBoost(12.0).
- BoostMode("multiply").
- ScoreMode("max")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"boost":2,"boost_mode":"multiply","field_value_factor":{"factor":2,"field":"income","modifier":"sqrt"},"max_boost":12,"query":{"term":{"name.last":"banon"}},"score_mode":"max","weight":2.5}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldValueFactorWithMultipleScoreFuncsAndWeights(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- AddScoreFunc(NewFieldValueFactorFunction().Modifier("sqrt").Factor(2).Field("income").Weight(2.5)).
- AddScoreFunc(NewScriptFunction(NewScript("_score * doc['my_numeric_field'].value")).Weight(1.25)).
- AddScoreFunc(NewWeightFactorFunction(0.5)).
- Boost(2.0).
- MaxBoost(12.0).
- BoostMode("multiply").
- ScoreMode("max")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"boost":2,"boost_mode":"multiply","functions":[{"field_value_factor":{"factor":2,"field":"income","modifier":"sqrt"},"weight":2.5},{"script_score":{"script":{"source":"_score * doc['my_numeric_field'].value"}},"weight":1.25},{"weight":0.5}],"max_boost":12,"query":{"term":{"name.last":"banon"}},"score_mode":"max"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFunctionScoreQueryWithGaussScoreFunc(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- AddScoreFunc(NewGaussDecayFunction().FieldName("pin.location").Origin("11, 12").Scale("2km").Offset("0km").Decay(0.33))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"gauss":{"pin.location":{"decay":0.33,"offset":"0km","origin":"11, 12","scale":"2km"}},"query":{"term":{"name.last":"banon"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFunctionScoreQueryWithGaussScoreFuncAndMultiValueMode(t *testing.T) {
- q := NewFunctionScoreQuery().
- Query(NewTermQuery("name.last", "banon")).
- AddScoreFunc(NewGaussDecayFunction().FieldName("pin.location").Origin("11, 12").Scale("2km").Offset("0km").Decay(0.33).MultiValueMode("avg"))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"function_score":{"gauss":{"multi_value_mode":"avg","pin.location":{"decay":0.33,"offset":"0km","origin":"11, 12","scale":"2km"}},"query":{"term":{"name.last":"banon"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy.go
index 02b6c52c2..b98f9c7f0 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy.go
@@ -8,7 +8,7 @@ package elastic
// string fields, and a +/- margin on numeric and date fields.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-fuzzy-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-fuzzy-query.html
type FuzzyQuery struct {
name string
value interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy_test.go
deleted file mode 100644
index 89140ca23..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_fuzzy_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestFuzzyQuery(t *testing.T) {
- q := NewFuzzyQuery("user", "ki").Boost(1.5).Fuzziness(2).PrefixLength(0).MaxExpansions(100)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"fuzzy":{"user":{"boost":1.5,"fuzziness":2,"max_expansions":100,"prefix_length":0,"value":"ki"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box.go
index 0418620d8..e53340e64 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box.go
@@ -10,7 +10,7 @@ import "errors"
// a bounding box.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-geo-bounding-box-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-geo-bounding-box-query.html
type GeoBoundingBoxQuery struct {
name string
top *float64
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box_test.go
deleted file mode 100644
index f44a2364f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_bounding_box_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoBoundingBoxQueryIncomplete(t *testing.T) {
- q := NewGeoBoundingBoxQuery("pin.location")
- q = q.TopLeft(40.73, -74.1)
- // no bottom and no right here
- q = q.Type("memory")
- src, err := q.Source()
- if err == nil {
- t.Fatal("expected error")
- }
- if src != nil {
- t.Fatal("expected empty source")
- }
-}
-
-func TestGeoBoundingBoxQuery(t *testing.T) {
- q := NewGeoBoundingBoxQuery("pin.location")
- q = q.TopLeft(40.73, -74.1)
- q = q.BottomRight(40.01, -71.12)
- q = q.Type("memory")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_bounding_box":{"pin.location":{"bottom_right":[-71.12,40.01],"top_left":[-74.1,40.73]},"type":"memory"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoBoundingBoxQueryWithGeoPoint(t *testing.T) {
- q := NewGeoBoundingBoxQuery("pin.location")
- q = q.TopLeftFromGeoPoint(GeoPointFromLatLon(40.73, -74.1))
- q = q.BottomRightFromGeoPoint(GeoPointFromLatLon(40.01, -71.12))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_bounding_box":{"pin.location":{"bottom_right":[-71.12,40.01],"top_left":[-74.1,40.73]}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance.go
index 00e62725f..a10bd5e3c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance.go
@@ -8,7 +8,7 @@ package elastic
// within a specific distance from a geo point.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-geo-distance-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-geo-distance-query.html
type GeoDistanceQuery struct {
name string
distance string
@@ -16,6 +16,7 @@ type GeoDistanceQuery struct {
lon float64
geohash string
distanceType string
+ optimizeBbox string
queryName string
}
@@ -61,6 +62,11 @@ func (q *GeoDistanceQuery) DistanceType(distanceType string) *GeoDistanceQuery {
return q
}
+func (q *GeoDistanceQuery) OptimizeBbox(optimizeBbox string) *GeoDistanceQuery {
+ q.optimizeBbox = optimizeBbox
+ return q
+}
+
func (q *GeoDistanceQuery) QueryName(queryName string) *GeoDistanceQuery {
q.queryName = queryName
return q
@@ -97,6 +103,9 @@ func (q *GeoDistanceQuery) Source() (interface{}, error) {
if q.distanceType != "" {
params["distance_type"] = q.distanceType
}
+ if q.optimizeBbox != "" {
+ params["optimize_bbox"] = q.optimizeBbox
+ }
if q.queryName != "" {
params["_name"] = q.queryName
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance_test.go
deleted file mode 100644
index dd169575a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoDistanceQuery(t *testing.T) {
- q := NewGeoDistanceQuery("pin.location")
- q = q.Lat(40)
- q = q.Lon(-70)
- q = q.Distance("200km")
- q = q.DistanceType("plane")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"distance":"200km","distance_type":"plane","pin.location":{"lat":40,"lon":-70}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceQueryWithGeoPoint(t *testing.T) {
- q := NewGeoDistanceQuery("pin.location")
- q = q.GeoPoint(GeoPointFromLatLon(40, -70))
- q = q.Distance("200km")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"distance":"200km","pin.location":{"lat":40,"lon":-70}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceQueryWithGeoHash(t *testing.T) {
- q := NewGeoDistanceQuery("pin.location")
- q = q.GeoHash("drm3btev3e86")
- q = q.Distance("12km")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_distance":{"distance":"12km","pin.location":"drm3btev3e86"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon.go
index 7678c3f3b..1faaf24e0 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon.go
@@ -7,7 +7,7 @@ package elastic
// GeoPolygonQuery allows to include hits that only fall within a polygon of points.
//
// For more details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-geo-polygon-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-geo-polygon-query.html
type GeoPolygonQuery struct {
name string
points []*GeoPoint
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon_test.go
deleted file mode 100644
index 932c57d7b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_polygon_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestGeoPolygonQuery(t *testing.T) {
- q := NewGeoPolygonQuery("person.location")
- q = q.AddPoint(40, -70)
- q = q.AddPoint(30, -80)
- point, err := GeoPointFromString("20,-90")
- if err != nil {
- t.Fatalf("GeoPointFromString failed: %v", err)
- }
- q = q.AddGeoPoint(point)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_polygon":{"person.location":{"points":[{"lat":40,"lon":-70},{"lat":30,"lon":-80},{"lat":20,"lon":-90}]}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoPolygonQueryFromGeoPoints(t *testing.T) {
- q := NewGeoPolygonQuery("person.location")
- q = q.AddGeoPoint(&GeoPoint{Lat: 40, Lon: -70})
- q = q.AddGeoPoint(GeoPointFromLatLon(30, -80))
- point, err := GeoPointFromString("20,-90")
- if err != nil {
- t.Fatalf("GeoPointFromString failed: %v", err)
- }
- q = q.AddGeoPoint(point)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"geo_polygon":{"person.location":{"points":[{"lat":40,"lon":-70},{"lat":30,"lon":-80},{"lat":20,"lon":-90}]}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child.go
index 41e7429c4..27cea7ad6 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child.go
@@ -8,7 +8,7 @@ package elastic
// in parent documents that have child docs matching the query.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-has-child-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-has-child-query.html
type HasChildQuery struct {
query Query
childType string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child_test.go
deleted file mode 100644
index 745c263f9..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_child_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestHasChildQuery(t *testing.T) {
- q := NewHasChildQuery("blog_tag", NewTermQuery("tag", "something")).ScoreMode("min")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"has_child":{"query":{"term":{"tag":"something"}},"score_mode":"min","type":"blog_tag"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestHasChildQueryWithInnerHit(t *testing.T) {
- q := NewHasChildQuery("blog_tag", NewTermQuery("tag", "something"))
- q = q.InnerHit(NewInnerHit().Name("comments"))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"has_child":{"inner_hits":{"name":"comments"},"query":{"term":{"tag":"something"}},"type":"blog_tag"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent.go
index 5e1b650af..7df110cd2 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent.go
@@ -11,7 +11,7 @@ package elastic
// same manner as has_child query.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-has-parent-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-has-parent-query.html
type HasParentQuery struct {
query Query
parentType string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent_test.go
deleted file mode 100644
index 0fec395e3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_has_parent_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestHasParentQueryTest(t *testing.T) {
- q := NewHasParentQuery("blog", NewTermQuery("tag", "something")).Score(true)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"has_parent":{"parent_type":"blog","query":{"term":{"tag":"something"}},"score":true}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids.go
index e067aebbe..42cc65672 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids.go
@@ -8,7 +8,7 @@ package elastic
// Note, this query uses the _uid field.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-ids-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-ids-query.html
type IdsQuery struct {
types []string
values []string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids_test.go
deleted file mode 100644
index b36605b4d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_ids_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestIdsQuery(t *testing.T) {
- q := NewIdsQuery("my_type").Ids("1", "4", "100").Boost(10.5).QueryName("my_query")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ids":{"_name":"my_query","boost":10.5,"type":"my_type","values":["1","4","100"]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_indices.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_indices.go
new file mode 100644
index 000000000..ed5ec9d84
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_indices.go
@@ -0,0 +1,89 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+// IndicesQuery can be used when executed across multiple indices, allowing
+// to have a query that executes only when executed on an index that matches
+// a specific list of indices, and another query that executes when it is
+// executed on an index that does not match the listed indices.
+//
+// For more details, see
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-indices-query.html
+type IndicesQuery struct {
+ query Query
+ indices []string
+ noMatchQueryType string
+ noMatchQuery Query
+ queryName string
+}
+
+// NewIndicesQuery creates and initializes a new indices query.
+func NewIndicesQuery(query Query, indices ...string) *IndicesQuery {
+ return &IndicesQuery{
+ query: query,
+ indices: indices,
+ }
+}
+
+// NoMatchQuery sets the query to use when it executes on an index that
+// does not match the indices provided.
+func (q *IndicesQuery) NoMatchQuery(query Query) *IndicesQuery {
+ q.noMatchQuery = query
+ return q
+}
+
+// NoMatchQueryType sets the no match query which can be either all or none.
+func (q *IndicesQuery) NoMatchQueryType(typ string) *IndicesQuery {
+ q.noMatchQueryType = typ
+ return q
+}
+
+// QueryName sets the query name for the filter.
+func (q *IndicesQuery) QueryName(queryName string) *IndicesQuery {
+ q.queryName = queryName
+ return q
+}
+
+// Source returns JSON for the function score query.
+func (q *IndicesQuery) Source() (interface{}, error) {
+ // {
+ // "indices" : {
+ // "indices" : ["index1", "index2"],
+ // "query" : {
+ // "term" : { "tag" : "wow" }
+ // },
+ // "no_match_query" : {
+ // "term" : { "tag" : "kow" }
+ // }
+ // }
+ // }
+
+ source := make(map[string]interface{})
+ params := make(map[string]interface{})
+ source["indices"] = params
+
+ params["indices"] = q.indices
+
+ src, err := q.query.Source()
+ if err != nil {
+ return nil, err
+ }
+ params["query"] = src
+
+ if q.noMatchQuery != nil {
+ src, err := q.noMatchQuery.Source()
+ if err != nil {
+ return nil, err
+ }
+ params["no_match_query"] = src
+ } else if q.noMatchQueryType != "" {
+ params["no_match_query"] = q.noMatchQueryType
+ }
+ if q.queryName != "" {
+ params["_name"] = q.queryName
+ }
+
+ return source, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match.go
index b38b12452..1f2f16f69 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match.go
@@ -12,7 +12,7 @@ package elastic
// or use one of the shortcuts e.g. NewMatchPhraseQuery(...).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-match-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-match-query.html
type MatchQuery struct {
name string
text interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all.go
index 3829c8af0..5551eea30 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all.go
@@ -8,7 +8,7 @@ package elastic
// giving them all a _score of 1.0.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-match-all-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-match-all-query.html
type MatchAllQuery struct {
boost *float64
queryName string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all_test.go
deleted file mode 100644
index 5d8671025..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_all_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatchAllQuery(t *testing.T) {
- q := NewMatchAllQuery()
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_all":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMatchAllQueryWithBoost(t *testing.T) {
- q := NewMatchAllQuery().Boost(3.14)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_all":{"boost":3.14}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMatchAllQueryWithQueryName(t *testing.T) {
- q := NewMatchAllQuery().QueryName("qname")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_all":{"_name":"qname"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none.go
index 9afe16716..06d036e71 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none.go
@@ -8,7 +8,7 @@ package elastic
// MatchAllQuery.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-match-all-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-match-all-query.html
type MatchNoneQuery struct {
queryName string
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none_test.go
deleted file mode 100644
index 6463452da..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_none_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatchNoneQuery(t *testing.T) {
- q := NewMatchNoneQuery()
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_none":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMatchNoneQueryWithQueryName(t *testing.T) {
- q := NewMatchNoneQuery().QueryName("qname")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_none":{"_name":"qname"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase.go
index 0e4c6327e..fdded2e76 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase.go
@@ -8,7 +8,7 @@ package elastic
// the analyzed text.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-match-query-phrase.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-match-query-phrase.html
type MatchPhraseQuery struct {
name string
value interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix.go
index 10a88668d..1eeba8af5 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix.go
@@ -8,7 +8,7 @@ package elastic
// prefix matches on the last term in the text.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-match-query-phrase-prefix.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-match-query-phrase-prefix.html
type MatchPhrasePrefixQuery struct {
name string
value interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix_test.go
deleted file mode 100644
index 82a02f17d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_prefix_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatchPhrasePrefixQuery(t *testing.T) {
- q := NewMatchPhrasePrefixQuery("message", "this is a test").Boost(0.3).MaxExpansions(5)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_phrase_prefix":{"message":{"boost":0.3,"max_expansions":5,"query":"this is a test"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_test.go
deleted file mode 100644
index 85e60d8b5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_phrase_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatchPhraseQuery(t *testing.T) {
- q := NewMatchPhraseQuery("message", "this is a test").
- Analyzer("my_analyzer").
- Boost(0.7)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_phrase":{"message":{"analyzer":"my_analyzer","boost":0.7,"query":"this is a test"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_test.go
deleted file mode 100644
index dd750cf93..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_match_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMatchQuery(t *testing.T) {
- q := NewMatchQuery("message", "this is a test")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match":{"message":{"query":"this is a test"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMatchQueryWithOptions(t *testing.T) {
- q := NewMatchQuery("message", "this is a test").Analyzer("whitespace").Operator("or").Boost(2.5)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match":{"message":{"analyzer":"whitespace","boost":2.5,"operator":"or","query":"this is a test"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this.go
index 5c71e291f..40c2d575d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this.go
@@ -13,7 +13,7 @@ import "errors"
// how the terms should be selected and how the query is formed.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-mlt-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-mlt-query.html
type MoreLikeThisQuery struct {
fields []string
docs []*MoreLikeThisQueryItem
@@ -25,8 +25,8 @@ type MoreLikeThisQuery struct {
stopWords []string
minDocFreq *int
maxDocFreq *int
- minWordLength *int
- maxWordLength *int
+ minWordLen *int
+ maxWordLen *int
boostTerms *float64
boost *float64
analyzer string
@@ -147,15 +147,15 @@ func (q *MoreLikeThisQuery) MaxDocFreq(maxDocFreq int) *MoreLikeThisQuery {
// MinWordLength sets the minimum word length below which words will be
// ignored. It defaults to 0.
-func (q *MoreLikeThisQuery) MinWordLength(minWordLength int) *MoreLikeThisQuery {
- q.minWordLength = &minWordLength
+func (q *MoreLikeThisQuery) MinWordLen(minWordLen int) *MoreLikeThisQuery {
+ q.minWordLen = &minWordLen
return q
}
-// MaxWordLength sets the maximum word length above which words will be ignored.
+// MaxWordLen sets the maximum word length above which words will be ignored.
// Defaults to unbounded (0).
-func (q *MoreLikeThisQuery) MaxWordLength(maxWordLength int) *MoreLikeThisQuery {
- q.maxWordLength = &maxWordLength
+func (q *MoreLikeThisQuery) MaxWordLen(maxWordLen int) *MoreLikeThisQuery {
+ q.maxWordLen = &maxWordLen
return q
}
@@ -254,11 +254,11 @@ func (q *MoreLikeThisQuery) Source() (interface{}, error) {
if q.maxDocFreq != nil {
params["max_doc_freq"] = *q.maxDocFreq
}
- if q.minWordLength != nil {
- params["min_word_length"] = *q.minWordLength
+ if q.minWordLen != nil {
+ params["min_word_len"] = *q.minWordLen
}
- if q.maxWordLength != nil {
- params["max_word_length"] = *q.maxWordLength
+ if q.maxWordLen != nil {
+ params["max_word_len"] = *q.maxWordLen
}
if q.boostTerms != nil {
params["boost_terms"] = *q.boostTerms
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this_test.go
deleted file mode 100644
index dcbbe74d1..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_more_like_this_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestMoreLikeThisQuerySourceWithLikeText(t *testing.T) {
- q := NewMoreLikeThisQuery().LikeText("Golang topic").Field("message")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatal(err)
- }
- got := string(data)
- expected := `{"more_like_this":{"fields":["message"],"like":["Golang topic"]}}`
- if got != expected {
- t.Fatalf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMoreLikeThisQuerySourceWithLikeAndUnlikeItems(t *testing.T) {
- q := NewMoreLikeThisQuery()
- q = q.LikeItems(
- NewMoreLikeThisQueryItem().Id("1"),
- NewMoreLikeThisQueryItem().Index(testIndexName2).Type("comment").Id("2").Routing("routing_id"),
- )
- q = q.IgnoreLikeItems(NewMoreLikeThisQueryItem().Id("3"))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatal(err)
- }
- got := string(data)
- expected := `{"more_like_this":{"like":[{"_id":"1"},{"_id":"2","_index":"elastic-test2","_routing":"routing_id","_type":"comment"}],"unlike":[{"_id":"3"}]}}`
- if got != expected {
- t.Fatalf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMoreLikeThisQuery(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another Golang topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Common query
- mltq := NewMoreLikeThisQuery().LikeText("Golang topic").Field("message")
- res, err := client.Search().
- Index(testIndexName).
- Query(mltq).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match.go
index b6ff2107e..9a149fed5 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match.go
@@ -12,7 +12,7 @@ import (
// MultiMatchQuery builds on the MatchQuery to allow multi-field queries.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-multi-match-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-multi-match-query.html
type MultiMatchQuery struct {
text interface{}
fields []string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match_test.go
deleted file mode 100644
index d897f7e72..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_multi_match_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestMultiMatchQuery(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryBestFields(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").Type("best_fields")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":0,"type":"best_fields"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryMostFields(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").Type("most_fields")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":1,"type":"most_fields"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryCrossFields(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").Type("cross_fields")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":0,"type":"cross_fields"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryPhrase(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").Type("phrase")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":0,"type":"phrase"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryPhrasePrefix(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").Type("phrase_prefix")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":0,"type":"phrase_prefix"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestMultiMatchQueryBestFieldsWithCustomTieBreaker(t *testing.T) {
- q := NewMultiMatchQuery("this is a test", "subject", "message").
- Type("best_fields").
- TieBreaker(0.3)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"multi_match":{"fields":["subject","message"],"query":"this is a test","tie_breaker":0.3,"type":"best_fields"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested.go
index d0a342283..a95cc2b80 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested.go
@@ -10,7 +10,7 @@ package elastic
// root parent doc (or parent nested mapping).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-nested-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-nested-query.html
type NestedQuery struct {
query Query
path string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested_test.go
deleted file mode 100644
index c7a5322a6..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_nested_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestNestedQuery(t *testing.T) {
- bq := NewBoolQuery()
- bq = bq.Must(NewTermQuery("obj1.name", "blue"))
- bq = bq.Must(NewRangeQuery("obj1.count").Gt(5))
- q := NewNestedQuery("obj1", bq).QueryName("qname")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"nested":{"_name":"qname","path":"obj1","query":{"bool":{"must":[{"term":{"obj1.name":"blue"}},{"range":{"obj1.count":{"from":5,"include_lower":false,"include_upper":true,"to":null}}}]}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNestedQueryWithInnerHit(t *testing.T) {
- bq := NewBoolQuery()
- bq = bq.Must(NewTermQuery("obj1.name", "blue"))
- bq = bq.Must(NewRangeQuery("obj1.count").Gt(5))
- q := NewNestedQuery("obj1", bq)
- q = q.QueryName("qname")
- q = q.InnerHit(NewInnerHit().Name("comments").Query(NewTermQuery("user", "olivere")))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"nested":{"_name":"qname","inner_hits":{"name":"comments","query":{"term":{"user":"olivere"}}},"path":"obj1","query":{"bool":{"must":[{"term":{"obj1.name":"blue"}},{"range":{"obj1.count":{"from":5,"include_lower":false,"include_upper":true,"to":null}}}]}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNestedQueryWithIgnoreUnmapped(t *testing.T) {
- var tests = []struct {
- query *BoolQuery
- expected string
- }{
- {
- NewBoolQuery().Must(NewNestedQuery("path", NewTermQuery("test", "test"))),
- `{"bool":{"must":{"nested":{"path":"path","query":{"term":{"test":"test"}}}}}}`,
- },
- {
- NewBoolQuery().Must(NewNestedQuery("path", NewTermQuery("test", "test")).IgnoreUnmapped(true)),
- `{"bool":{"must":{"nested":{"ignore_unmapped":true,"path":"path","query":{"term":{"test":"test"}}}}}}`,
- },
- {
- NewBoolQuery().Must(NewNestedQuery("path", NewTermQuery("test", "test")).IgnoreUnmapped(false)),
- `{"bool":{"must":{"nested":{"ignore_unmapped":false,"path":"path","query":{"term":{"test":"test"}}}}}}`,
- },
- }
- for _, test := range tests {
- src, err := test.query.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- if got != test.expected {
- t.Errorf("expected\n%s\n,got:\n%s", test.expected, got)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id.go
index c0b610f12..bd11cc291 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id.go
@@ -8,7 +8,7 @@ package elastic
// particular parent. Given the following mapping definition.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-parent-id-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-parent-id-query.html
type ParentIdQuery struct {
typ string
id string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id_test.go
deleted file mode 100644
index 0d18f216a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_parent_id_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestParentIdQueryTest(t *testing.T) {
- tests := []struct {
- Query Query
- Expected string
- }{
- // #0
- {
- Query: NewParentIdQuery("blog_tag", "1"),
- Expected: `{"parent_id":{"id":"1","type":"blog_tag"}}`,
- },
- // #1
- {
- Query: NewParentIdQuery("blog_tag", "1").IgnoreUnmapped(true),
- Expected: `{"parent_id":{"id":"1","ignore_unmapped":true,"type":"blog_tag"}}`,
- },
- // #2
- {
- Query: NewParentIdQuery("blog_tag", "1").IgnoreUnmapped(false),
- Expected: `{"parent_id":{"id":"1","ignore_unmapped":false,"type":"blog_tag"}}`,
- },
- // #3
- {
- Query: NewParentIdQuery("blog_tag", "1").IgnoreUnmapped(true).Boost(5).QueryName("my_parent_query"),
- Expected: `{"parent_id":{"_name":"my_parent_query","boost":5,"id":"1","ignore_unmapped":true,"type":"blog_tag"}}`,
- },
- }
-
- for i, tt := range tests {
- src, err := tt.Query.Source()
- if err != nil {
- t.Fatalf("#%d: encoding Source failed: %v", i, err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("#%d: marshaling to JSON failed: %v", i, err)
- }
- if want, got := tt.Expected, string(data); want != got {
- t.Fatalf("#%d: expected\n%s\ngot:\n%s", i, want, got)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator.go
index a7605655b..16f7611ed 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator.go
@@ -9,10 +9,10 @@ import "errors"
// PercolatorQuery can be used to match queries stored in an index.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-percolate-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.x/query-dsl-percolate-query.html
type PercolatorQuery struct {
field string
- documentType string // deprecated
+ documentType string
document interface{}
indexedDocumentIndex string
indexedDocumentType string
@@ -32,7 +32,6 @@ func (q *PercolatorQuery) Field(field string) *PercolatorQuery {
return q
}
-// Deprecated: DocumentType is deprecated as of 6.0.
func (q *PercolatorQuery) DocumentType(typ string) *PercolatorQuery {
q.documentType = typ
return q
@@ -78,6 +77,9 @@ func (q *PercolatorQuery) Source() (interface{}, error) {
if len(q.field) == 0 {
return nil, errors.New("elastic: Field is required in PercolatorQuery")
}
+ if len(q.documentType) == 0 {
+ return nil, errors.New("elastic: DocumentType is required in PercolatorQuery")
+ }
if q.document == nil {
return nil, errors.New("elastic: Document is required in PercolatorQuery")
}
@@ -89,9 +91,7 @@ func (q *PercolatorQuery) Source() (interface{}, error) {
params := make(map[string]interface{})
source["percolate"] = params
params["field"] = q.field
- if q.documentType != "" {
- params["document_type"] = q.documentType
- }
+ params["document_type"] = q.documentType
params["document"] = q.document
if len(q.indexedDocumentIndex) > 0 {
params["index"] = q.indexedDocumentIndex
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator_test.go
deleted file mode 100644
index edc7be626..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_percolator_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPercolatorQuery(t *testing.T) {
- q := NewPercolatorQuery().
- Field("query").
- Document(map[string]interface{}{
- "message": "Some message",
- })
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percolate":{"document":{"message":"Some message"},"field":"query"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercolatorQueryWithDetails(t *testing.T) {
- q := NewPercolatorQuery().
- Field("query").
- Document(map[string]interface{}{
- "message": "Some message",
- }).
- IndexedDocumentIndex("index").
- IndexedDocumentId("1").
- IndexedDocumentRouting("route").
- IndexedDocumentPreference("one").
- IndexedDocumentVersion(1)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"percolate":{"document":{"message":"Some message"},"field":"query","id":"1","index":"index","preference":"one","routing":"route","version":1}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPercolatorQueryWithMissingFields(t *testing.T) {
- q := NewPercolatorQuery() // no Field, Document, or Query
- _, err := q.Source()
- if err == nil {
- t.Fatal("expected error, got nil")
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix.go
index 075bcc7ba..0d5077553 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix.go
@@ -8,7 +8,7 @@ package elastic
// with a specified prefix (not analyzed).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-prefix-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-prefix-query.html
type PrefixQuery struct {
name string
prefix string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_example_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_example_test.go
deleted file mode 100644
index 73950f1f3..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_example_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic_test
-
-import (
- "context"
-
- "github.com/olivere/elastic"
-)
-
-func ExamplePrefixQuery() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Define wildcard query
- q := elastic.NewPrefixQuery("user", "oli")
- q = q.QueryName("my_query_name")
-
- searchResult, err := client.Search().
- Index("twitter").
- Query(q).
- Pretty(true).
- Do(context.Background())
- if err != nil {
- // Handle error
- panic(err)
- }
- _ = searchResult
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_test.go
deleted file mode 100644
index 78d27b600..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_prefix_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPrefixQuery(t *testing.T) {
- q := NewPrefixQuery("user", "ki")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"prefix":{"user":"ki"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPrefixQueryWithOptions(t *testing.T) {
- q := NewPrefixQuery("user", "ki")
- q = q.QueryName("my_query_name")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"prefix":{"user":{"_name":"my_query_name","value":"ki"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string.go
index a52c8b1a5..fa1393611 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string.go
@@ -11,36 +11,39 @@ import (
// QueryStringQuery uses the query parser in order to parse its content.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-query-string-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-query-string-query.html
type QueryStringQuery struct {
- queryString string
- defaultField string
- defaultOperator string
- analyzer string
- quoteAnalyzer string
- quoteFieldSuffix string
- allowLeadingWildcard *bool
- lowercaseExpandedTerms *bool // Deprecated: Decision is now made by the analyzer
- enablePositionIncrements *bool
- analyzeWildcard *bool
- locale string // Deprecated: Decision is now made by the analyzer
- boost *float64
- fuzziness string
- fuzzyPrefixLength *int
- fuzzyMaxExpansions *int
- fuzzyRewrite string
- phraseSlop *int
- fields []string
- fieldBoosts map[string]*float64
- tieBreaker *float64
- rewrite string
- minimumShouldMatch string
- lenient *bool
- queryName string
- timeZone string
- maxDeterminizedStates *int
- escape *bool
- typ string
+ queryString string
+ defaultField string
+ defaultOperator string
+ analyzer string
+ quoteAnalyzer string
+ quoteFieldSuffix string
+ autoGeneratePhraseQueries *bool
+ allowLeadingWildcard *bool
+ lowercaseExpandedTerms *bool
+ enablePositionIncrements *bool
+ analyzeWildcard *bool
+ locale string // Deprecated: Decision is now made by the analyzer.
+ boost *float64
+ fuzziness string
+ fuzzyPrefixLength *int
+ fuzzyMaxExpansions *int
+ fuzzyRewrite string
+ phraseSlop *int
+ fields []string
+ fieldBoosts map[string]*float64
+ useDisMax *bool
+ tieBreaker *float64
+ rewrite string
+ minimumShouldMatch string
+ lenient *bool
+ queryName string
+ timeZone string
+ maxDeterminizedStates *int
+ escape *bool
+ splitOnWhitespace *bool
+ useAllFields *bool
}
// NewQueryStringQuery creates and initializes a new QueryStringQuery.
@@ -66,10 +69,11 @@ func (q *QueryStringQuery) Field(field string) *QueryStringQuery {
return q
}
-// Type sets how multiple fields should be combined to build textual part queries,
-// e.g. "best_fields".
-func (q *QueryStringQuery) Type(typ string) *QueryStringQuery {
- q.typ = typ
+// AllFields tells the query string query to use all fields explicitly,
+// even if _all is enabled. If the "default_field" parameter or "fields"
+// are specified, they will be ignored.
+func (q *QueryStringQuery) AllFields(useAllFields bool) *QueryStringQuery {
+ q.useAllFields = &useAllFields
return q
}
@@ -80,6 +84,14 @@ func (q *QueryStringQuery) FieldWithBoost(field string, boost float64) *QueryStr
return q
}
+// UseDisMax specifies whether to combine queries using dis max or boolean
+// query when more zhan one field is used with the query string. Defaults
+// to dismax (true).
+func (q *QueryStringQuery) UseDisMax(useDisMax bool) *QueryStringQuery {
+ q.useDisMax = &useDisMax
+ return q
+}
+
// TieBreaker is used when more than one field is used with the query string,
// and combined queries are using dismax.
func (q *QueryStringQuery) TieBreaker(tieBreaker float64) *QueryStringQuery {
@@ -117,6 +129,15 @@ func (q *QueryStringQuery) QuoteAnalyzer(quoteAnalyzer string) *QueryStringQuery
return q
}
+// AutoGeneratePhraseQueries indicates whether or not phrase queries will
+// be automatically generated when the analyzer returns more then one term
+// from whitespace delimited text. Set to false if phrase queries should only
+// be generated when surrounded by double quotes.
+func (q *QueryStringQuery) AutoGeneratePhraseQueries(autoGeneratePhraseQueries bool) *QueryStringQuery {
+ q.autoGeneratePhraseQueries = &autoGeneratePhraseQueries
+ return q
+}
+
// MaxDeterminizedState protects against too-difficult regular expression queries.
func (q *QueryStringQuery) MaxDeterminizedState(maxDeterminizedStates int) *QueryStringQuery {
q.maxDeterminizedStates = &maxDeterminizedStates
@@ -132,8 +153,6 @@ func (q *QueryStringQuery) AllowLeadingWildcard(allowLeadingWildcard bool) *Quer
// LowercaseExpandedTerms indicates whether terms of wildcard, prefix, fuzzy
// and range queries are automatically lower-cased or not. Default is true.
-//
-// Deprecated: Decision is now made by the analyzer.
func (q *QueryStringQuery) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *QueryStringQuery {
q.lowercaseExpandedTerms = &lowercaseExpandedTerms
return q
@@ -245,6 +264,13 @@ func (q *QueryStringQuery) Escape(escape bool) *QueryStringQuery {
return q
}
+// SplitOnWhitespace indicates whether query text should be split on whitespace
+// prior to analysis.
+func (q *QueryStringQuery) SplitOnWhitespace(splitOnWhitespace bool) *QueryStringQuery {
+ q.splitOnWhitespace = &splitOnWhitespace
+ return q
+}
+
// Source returns JSON for the query.
func (q *QueryStringQuery) Source() (interface{}, error) {
source := make(map[string]interface{})
@@ -276,6 +302,9 @@ func (q *QueryStringQuery) Source() (interface{}, error) {
if q.tieBreaker != nil {
query["tie_breaker"] = *q.tieBreaker
}
+ if q.useDisMax != nil {
+ query["use_dis_max"] = *q.useDisMax
+ }
if q.defaultOperator != "" {
query["default_operator"] = q.defaultOperator
}
@@ -285,6 +314,9 @@ func (q *QueryStringQuery) Source() (interface{}, error) {
if q.quoteAnalyzer != "" {
query["quote_analyzer"] = q.quoteAnalyzer
}
+ if q.autoGeneratePhraseQueries != nil {
+ query["auto_generate_phrase_queries"] = *q.autoGeneratePhraseQueries
+ }
if q.maxDeterminizedStates != nil {
query["max_determinized_states"] = *q.maxDeterminizedStates
}
@@ -342,8 +374,11 @@ func (q *QueryStringQuery) Source() (interface{}, error) {
if q.escape != nil {
query["escape"] = *q.escape
}
- if q.typ != "" {
- query["type"] = q.typ
+ if q.splitOnWhitespace != nil {
+ query["split_on_whitespace"] = *q.splitOnWhitespace
+ }
+ if q.useAllFields != nil {
+ query["all_fields"] = *q.useAllFields
}
return source, nil
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string_test.go
deleted file mode 100644
index 5030c3382..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_query_string_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestQueryStringQuery(t *testing.T) {
- q := NewQueryStringQuery(`this AND that OR thus`)
- q = q.DefaultField("content")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query_string":{"default_field":"content","query":"this AND that OR thus"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestQueryStringQueryTimeZone(t *testing.T) {
- q := NewQueryStringQuery(`tweet_date:[2015-01-01 TO 2017-12-31]`)
- q = q.TimeZone("Europe/Berlin")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query_string":{"query":"tweet_date:[2015-01-01 TO 2017-12-31]","time_zone":"Europe/Berlin"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_range.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_range.go
index 1b92dee23..da7b5f965 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_range.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_range.go
@@ -7,7 +7,7 @@ package elastic
// RangeQuery matches documents with fields that have terms within a certain range.
//
// For details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-range-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-range-query.html
type RangeQuery struct {
name string
from interface{}
@@ -18,6 +18,7 @@ type RangeQuery struct {
boost *float64
queryName string
format string
+ relation string
}
// NewRangeQuery creates and initializes a new RangeQuery.
@@ -112,6 +113,13 @@ func (q *RangeQuery) Format(format string) *RangeQuery {
return q
}
+// Relation is used for range fields. which can be one of
+// "within", "contains", "intersects" (default) and "disjoint".
+func (q *RangeQuery) Relation(relation string) *RangeQuery {
+ q.relation = relation
+ return q
+}
+
// Source returns JSON for the query.
func (q *RangeQuery) Source() (interface{}, error) {
source := make(map[string]interface{})
@@ -130,6 +138,9 @@ func (q *RangeQuery) Source() (interface{}, error) {
if q.format != "" {
params["format"] = q.format
}
+ if q.relation != "" {
+ params["relation"] = q.relation
+ }
if q.boost != nil {
params["boost"] = *q.boost
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_range_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_range_test.go
deleted file mode 100644
index 86d018a86..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_range_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestRangeQuery(t *testing.T) {
- q := NewRangeQuery("postDate").From("2010-03-01").To("2010-04-01").Boost(3)
- q = q.QueryName("my_query")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"_name":"my_query","postDate":{"boost":3,"from":"2010-03-01","include_lower":true,"include_upper":true,"to":"2010-04-01"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeQueryWithTimeZone(t *testing.T) {
- q := NewRangeQuery("born").
- Gte("2012-01-01").
- Lte("now").
- TimeZone("+1:00")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"born":{"from":"2012-01-01","include_lower":true,"include_upper":true,"time_zone":"+1:00","to":"now"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRangeQueryWithFormat(t *testing.T) {
- q := NewRangeQuery("born").
- Gte("2012/01/01").
- Lte("now").
- Format("yyyy/MM/dd")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"range":{"born":{"format":"yyyy/MM/dd","from":"2012/01/01","include_lower":true,"include_upper":true,"to":"now"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_raw_string_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_raw_string_test.go
deleted file mode 100644
index 5bb3dac41..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_raw_string_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestRawStringQuery(t *testing.T) {
- q := RawStringQuery(`{"match_all":{}}`)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_all":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNewRawStringQuery(t *testing.T) {
- q := NewRawStringQuery(`{"match_all":{}}`)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"match_all":{}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp.go
index a08b533cb..636e4baf9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp.go
@@ -7,7 +7,7 @@ package elastic
// RegexpQuery allows you to use regular expression term queries.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-regexp-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-regexp-query.html
type RegexpQuery struct {
name string
regexp string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp_test.go
deleted file mode 100644
index d30c0a36d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_regexp_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestRegexpQuery(t *testing.T) {
- q := NewRegexpQuery("name.first", "s.*y")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"regexp":{"name.first":{"value":"s.*y"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestRegexpQueryWithOptions(t *testing.T) {
- q := NewRegexpQuery("name.first", "s.*y").
- Boost(1.2).
- Flags("INTERSECTION|COMPLEMENT|EMPTY").
- QueryName("my_query_name")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"regexp":{"name.first":{"boost":1.2,"flags":"INTERSECTION|COMPLEMENT|EMPTY","name":"my_query_name","value":"s.*y"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_script.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_script.go
index d430f4c8f..664555b3e 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_script.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_script.go
@@ -9,7 +9,7 @@ import "errors"
// ScriptQuery allows to define scripts as filters.
//
// For details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-script-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-script-query.html
type ScriptQuery struct {
script *Script
queryName string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_script_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_script_test.go
deleted file mode 100644
index 66ec106d5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_script_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestScriptQuery(t *testing.T) {
- q := NewScriptQuery(NewScript("doc['num1'.value > 1"))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"script":{"script":{"source":"doc['num1'.value \u003e 1"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScriptQueryWithParams(t *testing.T) {
- q := NewScriptQuery(NewScript("doc['num1'.value > 1"))
- q = q.QueryName("MyQueryName")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"script":{"_name":"MyQueryName","script":{"source":"doc['num1'.value \u003e 1"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string.go
index 462ea5533..764fa0a20 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string.go
@@ -15,7 +15,7 @@ import (
// and discards invalid parts of the query.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-simple-query-string-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-simple-query-string-query.html
type SimpleQueryStringQuery struct {
queryText string
analyzer string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string_test.go
deleted file mode 100644
index ea4a341ec..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_simple_query_string_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestSimpleQueryStringQuery(t *testing.T) {
- q := NewSimpleQueryStringQuery(`"fried eggs" +(eggplant | potato) -frittata`)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"simple_query_string":{"query":"\"fried eggs\" +(eggplant | potato) -frittata"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSimpleQueryStringQueryExec(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewSimpleQueryStringQuery("+Golang +Elasticsearch")).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 1 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 1 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 1, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice.go
index e1b1db928..0ebf88009 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice.go
@@ -6,7 +6,7 @@ package elastic
// SliceQuery allows to partition the documents into several slices.
// It is used e.g. to slice scroll operations in Elasticsearch 5.0 or later.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html#sliced-scroll
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#sliced-scroll
// for details.
type SliceQuery struct {
field string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice_test.go
deleted file mode 100644
index 0589f4e29..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_slice_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSliceQuery(t *testing.T) {
- q := NewSliceQuery().Field("date").Id(0).Max(2)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"field":"date","id":0,"max":2}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_term.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_term.go
index 9a445e0ec..051f6dee3 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_term.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_term.go
@@ -8,7 +8,7 @@ package elastic
// in the inverted index.
//
// For details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-term-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-term-query.html
type TermQuery struct {
name string
value interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_term_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_term_test.go
deleted file mode 100644
index f800fa954..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_term_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTermQuery(t *testing.T) {
- q := NewTermQuery("user", "ki")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"term":{"user":"ki"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermQueryWithOptions(t *testing.T) {
- q := NewTermQuery("user", "ki")
- q = q.Boost(2.79)
- q = q.QueryName("my_tq")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"term":{"user":{"_name":"my_tq","boost":2.79,"value":"ki"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms.go
index 3649576dc..794c1f31c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms.go
@@ -8,7 +8,7 @@ package elastic
// of the provided terms (not analyzed).
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-terms-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-terms-query.html
type TermsQuery struct {
name string
values []interface{}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set.go
deleted file mode 100644
index be410a1a7..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set.go
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-// TermsSetQuery returns any documents that match with at least
-// one or more of the provided terms. The terms are not analyzed
-// and thus must match exactly. The number of terms that must
-// match varies per document and is either controlled by a
-// minimum should match field or computed per document in a
-// minimum should match script.
-//
-// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-terms-set-query.html
-type TermsSetQuery struct {
- name string
- values []interface{}
- minimumShouldMatchField string
- minimumShouldMatchScript *Script
- queryName string
- boost *float64
-}
-
-// NewTermsSetQuery creates and initializes a new TermsSetQuery.
-func NewTermsSetQuery(name string, values ...interface{}) *TermsSetQuery {
- q := &TermsSetQuery{
- name: name,
- }
- if len(values) > 0 {
- q.values = append(q.values, values...)
- }
- return q
-}
-
-// MinimumShouldMatchField specifies the field to match.
-func (q *TermsSetQuery) MinimumShouldMatchField(minimumShouldMatchField string) *TermsSetQuery {
- q.minimumShouldMatchField = minimumShouldMatchField
- return q
-}
-
-// MinimumShouldMatchScript specifies the script to match.
-func (q *TermsSetQuery) MinimumShouldMatchScript(minimumShouldMatchScript *Script) *TermsSetQuery {
- q.minimumShouldMatchScript = minimumShouldMatchScript
- return q
-}
-
-// Boost sets the boost for this query.
-func (q *TermsSetQuery) Boost(boost float64) *TermsSetQuery {
- q.boost = &boost
- return q
-}
-
-// QueryName sets the query name for the filter that can be used
-// when searching for matched_filters per hit
-func (q *TermsSetQuery) QueryName(queryName string) *TermsSetQuery {
- q.queryName = queryName
- return q
-}
-
-// Source creates the query source for the term query.
-func (q *TermsSetQuery) Source() (interface{}, error) {
- // {"terms_set":{"codes":{"terms":["abc","def"],"minimum_should_match_field":"required_matches"}}}
- source := make(map[string]interface{})
- inner := make(map[string]interface{})
- params := make(map[string]interface{})
- inner[q.name] = params
- source["terms_set"] = inner
-
- // terms
- params["terms"] = q.values
-
- // minimum_should_match_field
- if match := q.minimumShouldMatchField; match != "" {
- params["minimum_should_match_field"] = match
- }
-
- // minimum_should_match_script
- if match := q.minimumShouldMatchScript; match != nil {
- src, err := match.Source()
- if err != nil {
- return nil, err
- }
- params["minimum_should_match_script"] = src
- }
-
- // Common parameters for all queries
- if q.boost != nil {
- params["boost"] = *q.boost
- }
- if q.queryName != "" {
- params["_name"] = q.queryName
- }
-
- return source, nil
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set_test.go
deleted file mode 100644
index e13fbfb2f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_set_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestTermsSetQueryWithField(t *testing.T) {
- q := NewTermsSetQuery("codes", "abc", "def", "ghi").MinimumShouldMatchField("required_matches")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms_set":{"codes":{"minimum_should_match_field":"required_matches","terms":["abc","def","ghi"]}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsSetQueryWithScript(t *testing.T) {
- q := NewTermsSetQuery("codes", "abc", "def", "ghi").
- MinimumShouldMatchScript(
- NewScript(`Math.min(params.num_terms, doc['required_matches'].value)`),
- )
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms_set":{"codes":{"minimum_should_match_script":{"source":"Math.min(params.num_terms, doc['required_matches'].value)"},"terms":["abc","def","ghi"]}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchTermsSetQuery(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(
- NewTermsSetQuery("user", "olivere", "sandrae").
- MinimumShouldMatchField("retweets"),
- ).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if got, want := searchResult.Hits.TotalHits, int64(3); got != want {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
- }
- if got, want := len(searchResult.Hits.Hits), 3; got != want {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_test.go
deleted file mode 100644
index 72f472d17..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_terms_test.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTermsQuery(t *testing.T) {
- q := NewTermsQuery("user", "ki")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"user":["ki"]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsQueryWithEmptyArray(t *testing.T) {
- included := make([]interface{}, 0)
- q := NewTermsQuery("tags", included...)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"tags":[]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermsQueryWithTermsLookup(t *testing.T) {
- q := NewTermsQuery("user").
- TermsLookup(NewTermsLookup().Index("users").Type("user").Id("2").Path("followers"))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"user":{"id":"2","index":"users","path":"followers","type":"user"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermQuerysWithOptions(t *testing.T) {
- q := NewTermsQuery("user", "ki", "ko")
- q = q.Boost(2.79)
- q = q.QueryName("my_tq")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"terms":{"_name":"my_tq","boost":2.79,"user":["ki","ko"]}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_type.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_type.go
index e7aef30df..70ace4541 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_type.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_type.go
@@ -7,7 +7,7 @@ package elastic
// TypeQuery filters documents matching the provided document / mapping type.
//
// For details, see:
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-type-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-type-query.html
type TypeQuery struct {
typ string
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_type_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_type_test.go
deleted file mode 100644
index 176b82abb..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_type_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTypeQuery(t *testing.T) {
- q := NewTypeQuery("my_type")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"type":{"value":"my_type"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard.go
index ea8a0901c..35f481542 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard.go
@@ -13,7 +13,7 @@ package elastic
// The wildcard query maps to Lucene WildcardQuery.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-wildcard-query.html
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-wildcard-query.html
type WildcardQuery struct {
name string
wildcard string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard_test.go
deleted file mode 100644
index b41c8ab7b..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_queries_wildcard_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic_test
-
-import (
- "context"
- "encoding/json"
- "testing"
-
- "github.com/olivere/elastic"
-)
-
-func ExampleWildcardQuery() {
- // Get a client to the local Elasticsearch instance.
- client, err := elastic.NewClient()
- if err != nil {
- // Handle error
- panic(err)
- }
-
- // Define wildcard query
- q := elastic.NewWildcardQuery("user", "oli*er?").Boost(1.2)
- searchResult, err := client.Search().
- Index("twitter"). // search in index "twitter"
- Query(q). // use wildcard query defined above
- Do(context.TODO()) // execute
- if err != nil {
- // Handle error
- panic(err)
- }
- _ = searchResult
-}
-
-func TestWildcardQuery(t *testing.T) {
- q := elastic.NewWildcardQuery("user", "ki*y??")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"wildcard":{"user":{"wildcard":"ki*y??"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestWildcardQueryWithBoost(t *testing.T) {
- q := elastic.NewWildcardQuery("user", "ki*y??").Boost(1.2)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"wildcard":{"user":{"boost":1.2,"wildcard":"ki*y??"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_request.go b/vendor/gopkg.in/olivere/elastic.v5/search_request.go
index 7ee4ce82c..f9dff52d9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_request.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_request.go
@@ -13,7 +13,7 @@ import (
// query details (see SearchSource).
// It is used in combination with MultiSearch.
type SearchRequest struct {
- searchType string // default in ES is "query_then_fetch"
+ searchType string
indices []string
types []string
routing *string
@@ -31,38 +31,29 @@ func NewSearchRequest() *SearchRequest {
return &SearchRequest{}
}
-// SearchRequest must be one of "query_then_fetch", "query_and_fetch",
-// "scan", "count", "dfs_query_then_fetch", or "dfs_query_and_fetch".
-// Use one of the constants defined via SearchType.
+// SearchRequest must be one of dfs_query_then_fetch, query_then_fetch
+// or query_and_fetch (deprecated in 5.3).
func (r *SearchRequest) SearchType(searchType string) *SearchRequest {
r.searchType = searchType
return r
}
+// SearchTypeDfsQueryThenFetch sets search type to dfs_query_then_fetch.
func (r *SearchRequest) SearchTypeDfsQueryThenFetch() *SearchRequest {
return r.SearchType("dfs_query_then_fetch")
}
-func (r *SearchRequest) SearchTypeDfsQueryAndFetch() *SearchRequest {
- return r.SearchType("dfs_query_and_fetch")
-}
-
+// SearchTypeQueryThenFetch sets search type to query_then_fetch.
func (r *SearchRequest) SearchTypeQueryThenFetch() *SearchRequest {
return r.SearchType("query_then_fetch")
}
+// SearchTypeQueryAndFetch sets search type to query_and_fetch which
+// was deprecated in 5.3.
func (r *SearchRequest) SearchTypeQueryAndFetch() *SearchRequest {
return r.SearchType("query_and_fetch")
}
-func (r *SearchRequest) SearchTypeScan() *SearchRequest {
- return r.SearchType("scan")
-}
-
-func (r *SearchRequest) SearchTypeCount() *SearchRequest {
- return r.SearchType("count")
-}
-
func (r *SearchRequest) Index(indices ...string) *SearchRequest {
r.indices = append(r.indices, indices...)
return r
@@ -139,7 +130,7 @@ func (r *SearchRequest) Source(source interface{}) *SearchRequest {
// header is used e.g. by MultiSearch to get information about the search header
// of one SearchRequest.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-multi-search.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-multi-search.html
func (r *SearchRequest) header() interface{} {
h := make(map[string]interface{})
if r.searchType != "" {
@@ -192,7 +183,7 @@ func (r *SearchRequest) header() interface{} {
//
// Body is used e.g. by MultiSearch to get information about the search body
// of one SearchRequest.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-multi-search.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-multi-search.html
func (r *SearchRequest) Body() (string, error) {
switch t := r.source.(type) {
default:
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_request_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_request_test.go
deleted file mode 100644
index fa03af2c8..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_request_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- _ "net/http"
- "testing"
-)
-
-func TestSearchRequestIndex(t *testing.T) {
- builder := NewSearchRequest().Index("test")
- data, err := json.Marshal(builder.header())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"index":"test"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchRequestIndices(t *testing.T) {
- builder := NewSearchRequest().Index("test", "test2")
- data, err := json.Marshal(builder.header())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"indices":["test","test2"]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchRequestHasIndices(t *testing.T) {
- builder := NewSearchRequest()
- if builder.HasIndices() {
- t.Errorf("expected HasIndices to return true; got %v", builder.HasIndices())
- }
- builder = builder.Index("test", "test2")
- if !builder.HasIndices() {
- t.Errorf("expected HasIndices to return false; got %v", builder.HasIndices())
- }
-}
-
-func TestSearchRequestIgnoreUnavailable(t *testing.T) {
- builder := NewSearchRequest().Index("test").IgnoreUnavailable(true)
- data, err := json.Marshal(builder.header())
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"ignore_unavailable":true,"index":"test"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_shards.go b/vendor/gopkg.in/olivere/elastic.v5/search_shards.go
new file mode 100644
index 000000000..edd9b0547
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_shards.go
@@ -0,0 +1,180 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// SearchShardsService returns the indices and shards that a search request would be executed against.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-shards.html
+type SearchShardsService struct {
+ client *Client
+ pretty bool
+ index []string
+ routing string
+ local *bool
+ preference string
+ ignoreUnavailable *bool
+ allowNoIndices *bool
+ expandWildcards string
+}
+
+// NewSearchShardsService creates a new SearchShardsService.
+func NewSearchShardsService(client *Client) *SearchShardsService {
+ return &SearchShardsService{
+ client: client,
+ }
+}
+
+// Index sets the names of the indices to restrict the results.
+func (s *SearchShardsService) Index(index ...string) *SearchShardsService {
+ s.index = append(s.index, index...)
+ return s
+}
+
+//A boolean value whether to read the cluster state locally in order to
+//determine where shards are allocated instead of using the Master node’s cluster state.
+func (s *SearchShardsService) Local(local bool) *SearchShardsService {
+ s.local = &local
+ return s
+}
+
+// Routing sets a specific routing value.
+func (s *SearchShardsService) Routing(routing string) *SearchShardsService {
+ s.routing = routing
+ return s
+}
+
+// Preference specifies the node or shard the operation should be performed on (default: random).
+func (s *SearchShardsService) Preference(preference string) *SearchShardsService {
+ s.preference = preference
+ return s
+}
+
+// Pretty indicates that the JSON response be indented and human readable.
+func (s *SearchShardsService) Pretty(pretty bool) *SearchShardsService {
+ s.pretty = pretty
+ return s
+}
+
+// IgnoreUnavailable indicates whether the specified concrete indices
+// should be ignored when unavailable (missing or closed).
+func (s *SearchShardsService) IgnoreUnavailable(ignoreUnavailable bool) *SearchShardsService {
+ s.ignoreUnavailable = &ignoreUnavailable
+ return s
+}
+
+// AllowNoIndices indicates whether to ignore if a wildcard indices
+// expression resolves into no concrete indices. (This includes `_all` string
+// or when no indices have been specified).
+func (s *SearchShardsService) AllowNoIndices(allowNoIndices bool) *SearchShardsService {
+ s.allowNoIndices = &allowNoIndices
+ return s
+}
+
+// ExpandWildcards indicates whether to expand wildcard expression to
+// concrete indices that are open, closed or both.
+func (s *SearchShardsService) ExpandWildcards(expandWildcards string) *SearchShardsService {
+ s.expandWildcards = expandWildcards
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *SearchShardsService) buildURL() (string, url.Values, error) {
+ // Build URL
+ path, err := uritemplates.Expand("/{index}/_search_shards", map[string]string{
+ "index": strings.Join(s.index, ","),
+ })
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.pretty {
+ params.Set("pretty", "true")
+ }
+ if s.preference != "" {
+ params.Set("preference", s.preference)
+ }
+ if s.local != nil {
+ params.Set("local", fmt.Sprintf("%v", *s.local))
+ }
+ if s.routing != "" {
+ params.Set("routing", s.routing)
+ }
+ if s.allowNoIndices != nil {
+ params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
+ }
+ if s.expandWildcards != "" {
+ params.Set("expand_wildcards", s.expandWildcards)
+ }
+ if s.ignoreUnavailable != nil {
+ params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
+ }
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *SearchShardsService) Validate() error {
+ var invalid []string
+ if len(s.index) < 1 {
+ invalid = append(invalid, "Index")
+ }
+ if len(invalid) > 0 {
+ return fmt.Errorf("missing required fields: %v", invalid)
+ }
+ return nil
+}
+
+// Do executes the operation.
+func (s *SearchShardsService) Do(ctx context.Context) (*SearchShardsResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return operation response
+ ret := new(SearchShardsResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+// SearchShardsResponse is the response of SearchShardsService.Do.
+type SearchShardsResponse struct {
+ Nodes map[string]interface{} `json:"nodes"`
+ Indices map[string]interface{} `json:"indices"`
+ Shards [][]ShardsInfo `json:"shards"`
+}
+
+type ShardsInfo struct {
+ Index string `json:"index"`
+ Node string `json:"node"`
+ Primary bool `json:"primary"`
+ Shard uint `json:"shard"`
+ State string `json:"state"`
+ AllocationId interface{} `json:"allocation_id"`
+ RelocatingNode bool `json:"relocating_node"`
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_source.go b/vendor/gopkg.in/olivere/elastic.v5/search_source.go
index 77b1c5093..be63b5cd9 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_source.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_source.go
@@ -77,7 +77,7 @@ func (s *SearchSource) PostFilter(postFilter Query) *SearchSource {
// Slice allows partitioning the documents in multiple slices.
// It is e.g. used to slice a scroll operation, supported in
// Elasticsearch 5.0 or later.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html#sliced-scroll
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#sliced-scroll
// for details.
func (s *SearchSource) Slice(sliceQuery Query) *SearchSource {
s.sliceQuery = sliceQuery
@@ -129,8 +129,8 @@ func (s *SearchSource) TimeoutInMillis(timeoutInMillis int) *SearchSource {
return s
}
-// TerminateAfter allows the request to stop after the given number
-// of search hits are collected.
+// TerminateAfter specifies the maximum number of documents to collect for
+// each shard, upon reaching which the query execution will terminate early.
func (s *SearchSource) TerminateAfter(terminateAfter int) *SearchSource {
s.terminateAfter = &terminateAfter
return s
@@ -168,7 +168,7 @@ func (s *SearchSource) TrackScores(trackScores bool) *SearchSource {
// SearchAfter allows a different form of pagination by using a live cursor,
// using the results of the previous page to help the retrieval of the next.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-search-after.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-search-after.html
func (s *SearchSource) SearchAfter(sortValues ...interface{}) *SearchSource {
s.searchAfterSortValues = append(s.searchAfterSortValues, sortValues...)
return s
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_source_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_source_test.go
deleted file mode 100644
index a78991bf0..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_source_test.go
+++ /dev/null
@@ -1,295 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSearchSourceMatchAllQuery(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceNoStoredFields(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).NoStoredFields()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceStoredFields(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).StoredFields("message", "tags")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}},"stored_fields":["message","tags"]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceFetchSourceDisabled(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).FetchSource(false)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_source":false,"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceFetchSourceByWildcards(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- fsc := NewFetchSourceContext(true).Include("obj1.*", "obj2.*").Exclude("*.description")
- builder := NewSearchSource().Query(matchAllQ).FetchSourceContext(fsc)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_source":{"excludes":["*.description"],"includes":["obj1.*","obj2.*"]},"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceDocvalueFields(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).DocvalueFields("test1", "test2")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"docvalue_fields":["test1","test2"],"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceScriptFields(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- sf1 := NewScriptField("test1", NewScript("doc['my_field_name'].value * 2"))
- sf2 := NewScriptField("test2", NewScript("doc['my_field_name'].value * factor").Param("factor", 3.1415927))
- builder := NewSearchSource().Query(matchAllQ).ScriptFields(sf1, sf2)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}},"script_fields":{"test1":{"script":{"source":"doc['my_field_name'].value * 2"}},"test2":{"script":{"params":{"factor":3.1415927},"source":"doc['my_field_name'].value * factor"}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourcePostFilter(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- pf := NewTermQuery("tag", "important")
- builder := NewSearchSource().Query(matchAllQ).PostFilter(pf)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"post_filter":{"term":{"tag":"important"}},"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceHighlight(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- hl := NewHighlight().Field("content")
- builder := NewSearchSource().Query(matchAllQ).Highlight(hl)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"highlight":{"fields":{"content":{}}},"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceRescoring(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- rescorerQuery := NewMatchPhraseQuery("field1", "the quick brown fox").Slop(2)
- rescorer := NewQueryRescorer(rescorerQuery)
- rescorer = rescorer.QueryWeight(0.7)
- rescorer = rescorer.RescoreQueryWeight(1.2)
- rescore := NewRescore().WindowSize(50).Rescorer(rescorer)
- builder := NewSearchSource().Query(matchAllQ).Rescorer(rescore)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}},"rescore":{"query":{"query_weight":0.7,"rescore_query":{"match_phrase":{"field1":{"query":"the quick brown fox","slop":2}}},"rescore_query_weight":1.2},"window_size":50}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceIndexBoost(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).IndexBoost("index1", 1.4).IndexBoost("index2", 1.3)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"indices_boost":{"index1":1.4,"index2":1.3},"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceMixDifferentSorters(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).
- Sort("a", false).
- SortWithInfo(SortInfo{Field: "b", Ascending: true}).
- SortBy(NewScriptSort(NewScript("doc['field_name'].value * factor").Param("factor", 1.1), "number"))
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}},"sort":[{"a":{"order":"desc"}},{"b":{"order":"asc"}},{"_script":{"order":"asc","script":{"params":{"factor":1.1},"source":"doc['field_name'].value * factor"},"type":"number"}}]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceInnerHits(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).
- InnerHit("comments", NewInnerHit().Type("comment").Query(NewMatchQuery("user", "olivere"))).
- InnerHit("views", NewInnerHit().Path("view"))
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"inner_hits":{"comments":{"type":{"comment":{"query":{"match":{"user":{"query":"olivere"}}}}}},"views":{"path":{"view":{}}}},"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceSearchAfter(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).SearchAfter(1463538857, "tweet#654323")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"query":{"match_all":{}},"search_after":[1463538857,"tweet#654323"]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSearchSourceProfiledQuery(t *testing.T) {
- matchAllQ := NewMatchAllQuery()
- builder := NewSearchSource().Query(matchAllQ).Profile(true)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"profile":true,"query":{"match_all":{}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_suggester_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_suggester_test.go
deleted file mode 100644
index 33bdc9275..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_suggester_test.go
+++ /dev/null
@@ -1,355 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestTermSuggester(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- tsName := "my-suggestions"
- ts := NewTermSuggester(tsName)
- ts = ts.Text("Goolang")
- ts = ts.Field("message")
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- Suggester(ts).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Suggest == nil {
- t.Errorf("expected SearchResult.Suggest != nil; got nil")
- }
- mySuggestions, found := searchResult.Suggest[tsName]
- if !found {
- t.Errorf("expected to find SearchResult.Suggest[%s]; got false", tsName)
- }
- if mySuggestions == nil {
- t.Errorf("expected SearchResult.Suggest[%s] != nil; got nil", tsName)
- }
-
- if len(mySuggestions) != 1 {
- t.Errorf("expected 1 suggestion; got %d", len(mySuggestions))
- }
- mySuggestion := mySuggestions[0]
- if mySuggestion.Text != "goolang" {
- t.Errorf("expected Text = 'goolang'; got %s", mySuggestion.Text)
- }
- if mySuggestion.Offset != 0 {
- t.Errorf("expected Offset = %d; got %d", 0, mySuggestion.Offset)
- }
- if mySuggestion.Length != 7 {
- t.Errorf("expected Length = %d; got %d", 7, mySuggestion.Length)
- }
- if len(mySuggestion.Options) != 1 {
- t.Errorf("expected 1 option; got %d", len(mySuggestion.Options))
- }
- myOption := mySuggestion.Options[0]
- if myOption.Text != "golang" {
- t.Errorf("expected Text = 'golang'; got %s", myOption.Text)
- }
-}
-
-func TestPhraseSuggester(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- phraseSuggesterName := "my-suggestions"
- ps := NewPhraseSuggester(phraseSuggesterName)
- ps = ps.Text("Goolang")
- ps = ps.Field("message")
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- Suggester(ps).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Suggest == nil {
- t.Errorf("expected SearchResult.Suggest != nil; got nil")
- }
- mySuggestions, found := searchResult.Suggest[phraseSuggesterName]
- if !found {
- t.Errorf("expected to find SearchResult.Suggest[%s]; got false", phraseSuggesterName)
- }
- if mySuggestions == nil {
- t.Errorf("expected SearchResult.Suggest[%s] != nil; got nil", phraseSuggesterName)
- }
-
- if len(mySuggestions) != 1 {
- t.Errorf("expected 1 suggestion; got %d", len(mySuggestions))
- }
- mySuggestion := mySuggestions[0]
- if mySuggestion.Text != "Goolang" {
- t.Errorf("expected Text = 'Goolang'; got %s", mySuggestion.Text)
- }
- if mySuggestion.Offset != 0 {
- t.Errorf("expected Offset = %d; got %d", 0, mySuggestion.Offset)
- }
- if mySuggestion.Length != 7 {
- t.Errorf("expected Length = %d; got %d", 7, mySuggestion.Length)
- }
- if want, have := 1, len(mySuggestion.Options); want != have {
- t.Errorf("expected len(options) = %d; got %d", want, have)
- }
- if want, have := "golang", mySuggestion.Options[0].Text; want != have {
- t.Errorf("expected options[0].Text = %q; got %q", want, have)
- }
- if score := mySuggestion.Options[0].Score; score <= 0.0 {
- t.Errorf("expected options[0].Score > 0.0; got %v", score)
- }
-}
-
-func TestCompletionSuggester(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- tweet1 := tweet{
- User: "olivere",
- Message: "Welcome to Golang and Elasticsearch.",
- Suggest: NewSuggestField("Golang", "Elasticsearch"),
- }
- tweet2 := tweet{
- User: "olivere",
- Message: "Another unrelated topic.",
- Suggest: NewSuggestField("Another unrelated topic."),
- }
- tweet3 := tweet{
- User: "sandrae",
- Message: "Cycling is fun.",
- Suggest: NewSuggestField("Cycling is fun."),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- suggesterName := "my-suggestions"
- cs := NewCompletionSuggester(suggesterName)
- cs = cs.Text("Golang")
- cs = cs.Field("suggest_field")
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- Suggester(cs).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Suggest == nil {
- t.Errorf("expected SearchResult.Suggest != nil; got nil")
- }
- mySuggestions, found := searchResult.Suggest[suggesterName]
- if !found {
- t.Errorf("expected to find SearchResult.Suggest[%s]; got false", suggesterName)
- }
- if mySuggestions == nil {
- t.Errorf("expected SearchResult.Suggest[%s] != nil; got nil", suggesterName)
- }
-
- if len(mySuggestions) != 1 {
- t.Errorf("expected 1 suggestion; got %d", len(mySuggestions))
- }
- mySuggestion := mySuggestions[0]
- if mySuggestion.Text != "Golang" {
- t.Errorf("expected Text = 'Golang'; got %s", mySuggestion.Text)
- }
- if mySuggestion.Offset != 0 {
- t.Errorf("expected Offset = %d; got %d", 0, mySuggestion.Offset)
- }
- if mySuggestion.Length != 6 {
- t.Errorf("expected Length = %d; got %d", 7, mySuggestion.Length)
- }
- if len(mySuggestion.Options) != 1 {
- t.Errorf("expected 1 option; got %d", len(mySuggestion.Options))
- }
- myOption := mySuggestion.Options[0]
- if myOption.Text != "Golang" {
- t.Errorf("expected Text = 'Golang'; got %s", myOption.Text)
- }
-}
-
-func TestContextSuggester(t *testing.T) {
- client := setupTestClientAndCreateIndex(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- // TODO make a nice way of creating tweets, as currently the context fields are unsupported as part of the suggestion fields
- tweet1 := `
- {
- "user":"olivere",
- "message":"Welcome to Golang and Elasticsearch.",
- "retweets":0,
- "created":"0001-01-01T00:00:00Z",
- "suggest_field":{
- "input":[
- "Golang",
- "Elasticsearch"
- ],
- "contexts":{
- "user_name": ["olivere"]
- }
- }
- }
- `
- tweet2 := `
- {
- "user":"sandrae",
- "message":"I like golfing",
- "retweets":0,
- "created":"0001-01-01T00:00:00Z",
- "suggest_field":{
- "input":[
- "Golfing"
- ],
- "contexts":{
- "user_name": ["sandrae"]
- }
- }
- }
- `
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyString(tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyString(tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- suggesterName := "my-suggestions"
- cs := NewContextSuggester(suggesterName)
- cs = cs.Prefix("Gol")
- cs = cs.Field("suggest_field")
- cs = cs.ContextQueries(
- NewSuggesterCategoryQuery("user_name", "olivere"),
- )
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Suggester(cs).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Suggest == nil {
- t.Errorf("expected SearchResult.Suggest != nil; got nil")
- }
- mySuggestions, found := searchResult.Suggest[suggesterName]
- if !found {
- t.Errorf("expected to find SearchResult.Suggest[%s]; got false", suggesterName)
- }
- if mySuggestions == nil {
- t.Errorf("expected SearchResult.Suggest[%s] != nil; got nil", suggesterName)
- }
-
- // sandra's tweet is not returned because of the user_name context
- if len(mySuggestions) != 1 {
- t.Errorf("expected 1 suggestion; got %d", len(mySuggestions))
- }
- mySuggestion := mySuggestions[0]
- if mySuggestion.Text != "Gol" {
- t.Errorf("expected Text = 'Gol'; got %s", mySuggestion.Text)
- }
- if mySuggestion.Offset != 0 {
- t.Errorf("expected Offset = %d; got %d", 0, mySuggestion.Offset)
- }
- if mySuggestion.Length != 3 {
- t.Errorf("expected Length = %d; got %d", 3, mySuggestion.Length)
- }
- if len(mySuggestion.Options) != 1 {
- t.Errorf("expected 1 option; got %d", len(mySuggestion.Options))
- }
- myOption := mySuggestion.Options[0]
- if myOption.Text != "Golang" {
- t.Errorf("expected Text = 'Golang'; got %s", myOption.Text)
- }
- if myOption.Id != "1" {
- t.Errorf("expected Id = '1'; got %s", myOption.Id)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup.go b/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup.go
index 9a2456bdd..e59e15c12 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup.go
@@ -7,7 +7,7 @@ package elastic
// TermsLookup encapsulates the parameters needed to fetch terms.
//
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-terms-query.html#query-dsl-terms-lookup.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.3/query-dsl-terms-query.html#query-dsl-terms-lookup.
type TermsLookup struct {
index string
typ string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup_test.go
deleted file mode 100644
index 369f72346..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_terms_lookup_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTermsLookup(t *testing.T) {
- tl := NewTermsLookup().Index("users").Type("user").Id("2").Path("followers")
- src, err := tl.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"id":"2","index":"users","path":"followers","type":"user"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/search_test.go b/vendor/gopkg.in/olivere/elastic.v5/search_test.go
deleted file mode 100644
index 586089aaa..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/search_test.go
+++ /dev/null
@@ -1,1320 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "reflect"
- "testing"
- "time"
-)
-
-func TestSearchMatchAll(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- Size(100).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if got, want := searchResult.Hits.TotalHits, int64(3); got != want {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
- }
- if got, want := len(searchResult.Hits.Hits), 3; got != want {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestSearchMatchAllWithRequestCacheDisabled(t *testing.T) {
- //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents, with request cache disabled
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- Size(100).
- Pretty(true).
- RequestCache(false).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if got, want := searchResult.Hits.TotalHits, int64(3); got != want {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
- }
- if got, want := len(searchResult.Hits.Hits), 3; got != want {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
- }
-}
-
-func BenchmarkSearchMatchAll(b *testing.B) {
- client := setupTestClientAndCreateIndexAndAddDocs(b)
-
- for n := 0; n < b.N; n++ {
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().Index(testIndexName).Query(all).Do(context.TODO())
- if err != nil {
- b.Fatal(err)
- }
- if searchResult.Hits == nil {
- b.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits == 0 {
- b.Errorf("expected SearchResult.Hits.TotalHits > %d; got %d", 0, searchResult.Hits.TotalHits)
- }
- }
-}
-
-func TestSearchResultTotalHits(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- count, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- all := NewMatchAllQuery()
- searchResult, err := client.Search().Index(testIndexName).Query(all).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- got := searchResult.TotalHits()
- if got != count {
- t.Fatalf("expected %d hits; got: %d", count, got)
- }
-
- // No hits
- searchResult = &SearchResult{}
- got = searchResult.TotalHits()
- if got != 0 {
- t.Errorf("expected %d hits; got: %d", 0, got)
- }
-}
-
-func TestSearchResultWithProfiling(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- all := NewMatchAllQuery()
- searchResult, err := client.Search().Index(testIndexName).Query(all).Profile(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- if searchResult.Profile == nil {
- t.Fatal("Profiled MatchAll query did not return profiling data with results")
- }
-}
-
-func TestSearchResultEach(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- all := NewMatchAllQuery()
- searchResult, err := client.Search().Index(testIndexName).Query(all).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Iterate over non-ptr type
- var aTweet tweet
- count := 0
- for _, item := range searchResult.Each(reflect.TypeOf(aTweet)) {
- count++
- _, ok := item.(tweet)
- if !ok {
- t.Fatalf("expected hit to be serialized as tweet; got: %v", reflect.ValueOf(item))
- }
- }
- if count == 0 {
- t.Errorf("expected to find some hits; got: %d", count)
- }
-
- // Iterate over ptr-type
- count = 0
- var aTweetPtr *tweet
- for _, item := range searchResult.Each(reflect.TypeOf(aTweetPtr)) {
- count++
- tw, ok := item.(*tweet)
- if !ok {
- t.Fatalf("expected hit to be serialized as tweet; got: %v", reflect.ValueOf(item))
- }
- if tw == nil {
- t.Fatal("expected hit to not be nil")
- }
- }
- if count == 0 {
- t.Errorf("expected to find some hits; got: %d", count)
- }
-
- // Does not iterate when no hits are found
- searchResult = &SearchResult{Hits: nil}
- count = 0
- for _, item := range searchResult.Each(reflect.TypeOf(aTweet)) {
- count++
- _ = item
- }
- if count != 0 {
- t.Errorf("expected to not find any hits; got: %d", count)
- }
- searchResult = &SearchResult{Hits: &SearchHits{Hits: make([]*SearchHit, 0)}}
- count = 0
- for _, item := range searchResult.Each(reflect.TypeOf(aTweet)) {
- count++
- _ = item
- }
- if count != 0 {
- t.Errorf("expected to not find any hits; got: %d", count)
- }
-}
-
-func TestSearchResultEachNoSource(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocsNoSource(t)
-
- all := NewMatchAllQuery()
- searchResult, err := client.Search().Index(testNoSourceIndexName).Query(all).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Iterate over non-ptr type
- var aTweet tweet
- count := 0
- for _, item := range searchResult.Each(reflect.TypeOf(aTweet)) {
- count++
- tw, ok := item.(tweet)
- if !ok {
- t.Fatalf("expected hit to be serialized as tweet; got: %v", reflect.ValueOf(item))
- }
-
- if tw.User != "" {
- t.Fatalf("expected no _source hit to be empty tweet; got: %v", reflect.ValueOf(item))
- }
- }
- if count != 2 {
- t.Errorf("expected to find 2 hits; got: %d", count)
- }
-
- // Iterate over ptr-type
- count = 0
- var aTweetPtr *tweet
- for _, item := range searchResult.Each(reflect.TypeOf(aTweetPtr)) {
- count++
- tw, ok := item.(*tweet)
- if !ok {
- t.Fatalf("expected hit to be serialized as tweet; got: %v", reflect.ValueOf(item))
- }
- if tw != nil {
- t.Fatal("expected hit to be nil")
- }
- }
- if count != 2 {
- t.Errorf("expected to find 2 hits; got: %d", count)
- }
-}
-
-func TestSearchSorting(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(all).
- Sort("created", false).
- Timeout("1s").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 3 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 3, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestSearchSortingBySorters(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(all).
- SortBy(NewFieldSort("created").Desc(), NewScoreSort()).
- Timeout("1s").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 3 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 3, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestSearchSpecificFields(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(all).
- StoredFields("message").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 3 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 3, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- if hit.Source != nil {
- t.Fatalf("expected SearchResult.Hits.Hit.Source to be nil; got: %q", hit.Source)
- }
- if hit.Fields == nil {
- t.Fatal("expected SearchResult.Hits.Hit.Fields to be != nil")
- }
- field, found := hit.Fields["message"]
- if !found {
- t.Errorf("expected SearchResult.Hits.Hit.Fields[%s] to be found", "message")
- }
- fields, ok := field.([]interface{})
- if !ok {
- t.Errorf("expected []interface{}; got: %v", reflect.TypeOf(fields))
- }
- if len(fields) != 1 {
- t.Errorf("expected a field with 1 entry; got: %d", len(fields))
- }
- message, ok := fields[0].(string)
- if !ok {
- t.Errorf("expected a string; got: %v", reflect.TypeOf(fields[0]))
- }
- if message == "" {
- t.Errorf("expected a message; got: %q", message)
- }
- }
-}
-
-func TestSearchExplain(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
- // client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(all).
- Explain(true).
- Timeout("1s").
- // Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 3 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 3, len(searchResult.Hits.Hits))
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- if hit.Explanation == nil {
- t.Fatal("expected search explanation")
- }
- if hit.Explanation.Value <= 0.0 {
- t.Errorf("expected explanation value to be > 0.0; got: %v", hit.Explanation.Value)
- }
- if hit.Explanation.Description == "" {
- t.Errorf("expected explanation description != %q; got: %q", "", hit.Explanation.Description)
- }
- }
-}
-
-func TestSearchSource(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Set up the request JSON manually to pass to the search service via Source()
- source := map[string]interface{}{
- "query": map[string]interface{}{
- "match_all": map[string]interface{}{},
- },
- }
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Source(source). // sets the JSON request
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
-}
-
-func TestSearchSourceWithString(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Source(`{"query":{"match_all":{}}}`). // sets the JSON request
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
-}
-
-func TestSearchRawString(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- query := RawStringQuery(`{"match_all":{}}`)
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(query).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
-}
-
-func TestSearchSearchSource(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- // Set up the search source manually and pass it to the search service via SearchSource()
- ss := NewSearchSource().Query(NewMatchAllQuery()).From(0).Size(2)
-
- // One can use ss.Source() to get to the raw interface{} that will be used
- // as the search request JSON by the SearchService.
-
- searchResult, err := client.Search().
- Index(testIndexName).
- SearchSource(ss). // sets the SearchSource
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 2 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 2, len(searchResult.Hits.Hits))
- }
-}
-
-func TestSearchInnerHitsOnHasChild(t *testing.T) {
- // client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- ctx := context.Background()
-
- // Create join index
- createIndex, err := client.CreateIndex(testJoinIndex).Body(testJoinMapping).Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex)
- }
-
- // Add documents
- // See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/parent-join.html for example code.
- doc1 := joinDoc{
- Message: "This is a question",
- JoinField: &joinField{Name: "question"},
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("1").BodyJson(&doc1).Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc2 := joinDoc{
- Message: "This is another question",
- JoinField: "question",
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("2").BodyJson(&doc2).Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc3 := joinDoc{
- Message: "This is an answer",
- JoinField: &joinField{
- Name: "answer",
- Parent: "1",
- },
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("3").BodyJson(&doc3).Routing("1").Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc4 := joinDoc{
- Message: "This is another answer",
- JoinField: &joinField{
- Name: "answer",
- Parent: "1",
- },
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("4").BodyJson(&doc4).Routing("1").Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testJoinIndex).Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
-
- // Search for all documents that have an answer, and return those answers as inner hits
- bq := NewBoolQuery()
- bq = bq.Must(NewMatchAllQuery())
- bq = bq.Filter(NewHasChildQuery("answer", NewMatchAllQuery()).
- InnerHit(NewInnerHit().Name("answers")))
-
- searchResult, err := client.Search().
- Index(testJoinIndex).
- Query(bq).
- Pretty(true).
- Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 1 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 2, searchResult.Hits.TotalHits)
- }
- if len(searchResult.Hits.Hits) != 1 {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 2, len(searchResult.Hits.Hits))
- }
-
- hit := searchResult.Hits.Hits[0]
- if want, have := "1", hit.Id; want != have {
- t.Fatalf("expected tweet %q; got: %q", want, have)
- }
- if hit.InnerHits == nil {
- t.Fatalf("expected inner hits; got: %v", hit.InnerHits)
- }
- if want, have := 1, len(hit.InnerHits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- innerHits, found := hit.InnerHits["answers"]
- if !found {
- t.Fatalf("expected inner hits for name %q", "answers")
- }
- if innerHits == nil || innerHits.Hits == nil {
- t.Fatal("expected inner hits != nil")
- }
- if want, have := 2, len(innerHits.Hits.Hits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- if want, have := "3", innerHits.Hits.Hits[0].Id; want != have {
- t.Fatalf("expected inner hit with id %q; got: %q", want, have)
- }
- if want, have := "4", innerHits.Hits.Hits[1].Id; want != have {
- t.Fatalf("expected inner hit with id %q; got: %q", want, have)
- }
-}
-
-func TestSearchInnerHitsOnHasParent(t *testing.T) {
- // client := setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- ctx := context.Background()
-
- // Create join index
- createIndex, err := client.CreateIndex(testJoinIndex).Body(testJoinMapping).Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex)
- }
-
- // Add documents
- // See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/parent-join.html for example code.
- doc1 := joinDoc{
- Message: "This is a question",
- JoinField: &joinField{Name: "question"},
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("1").BodyJson(&doc1).Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc2 := joinDoc{
- Message: "This is another question",
- JoinField: "question",
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("2").BodyJson(&doc2).Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc3 := joinDoc{
- Message: "This is an answer",
- JoinField: &joinField{
- Name: "answer",
- Parent: "1",
- },
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("3").BodyJson(&doc3).Routing("1").Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- doc4 := joinDoc{
- Message: "This is another answer",
- JoinField: &joinField{
- Name: "answer",
- Parent: "1",
- },
- }
- _, err = client.Index().Index(testJoinIndex).Type("doc").Id("4").BodyJson(&doc4).Routing("1").Refresh("true").Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testJoinIndex).Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
-
- // Search for all documents that have an answer, and return those answers as inner hits
- bq := NewBoolQuery()
- bq = bq.Must(NewMatchAllQuery())
- bq = bq.Filter(NewHasParentQuery("question", NewMatchAllQuery()).
- InnerHit(NewInnerHit().Name("answers")))
-
- searchResult, err := client.Search().
- Index(testJoinIndex).
- Query(bq).
- Pretty(true).
- Do(ctx)
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if want, have := int64(2), searchResult.Hits.TotalHits; want != have {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, have)
- }
- if want, have := 2, len(searchResult.Hits.Hits); want != have {
- t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, have)
- }
-
- hit := searchResult.Hits.Hits[0]
- if want, have := "3", hit.Id; want != have {
- t.Fatalf("expected tweet %q; got: %q", want, have)
- }
- if hit.InnerHits == nil {
- t.Fatalf("expected inner hits; got: %v", hit.InnerHits)
- }
- if want, have := 1, len(hit.InnerHits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- innerHits, found := hit.InnerHits["answers"]
- if !found {
- t.Fatalf("expected inner hits for name %q", "tweets")
- }
- if innerHits == nil || innerHits.Hits == nil {
- t.Fatal("expected inner hits != nil")
- }
- if want, have := 1, len(innerHits.Hits.Hits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- if want, have := "1", innerHits.Hits.Hits[0].Id; want != have {
- t.Fatalf("expected inner hit with id %q; got: %q", want, have)
- }
-
- hit = searchResult.Hits.Hits[1]
- if want, have := "4", hit.Id; want != have {
- t.Fatalf("expected tweet %q; got: %q", want, have)
- }
- if hit.InnerHits == nil {
- t.Fatalf("expected inner hits; got: %v", hit.InnerHits)
- }
- if want, have := 1, len(hit.InnerHits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- innerHits, found = hit.InnerHits["answers"]
- if !found {
- t.Fatalf("expected inner hits for name %q", "tweets")
- }
- if innerHits == nil || innerHits.Hits == nil {
- t.Fatal("expected inner hits != nil")
- }
- if want, have := 1, len(innerHits.Hits.Hits); want != have {
- t.Fatalf("expected %d inner hits; got: %d", want, have)
- }
- if want, have := "1", innerHits.Hits.Hits[0].Id; want != have {
- t.Fatalf("expected inner hit with id %q; got: %q", want, have)
- }
-}
-
-func TestSearchBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- }{
- {
- []string{},
- []string{},
- "/_search",
- },
- {
- []string{"index1"},
- []string{},
- "/index1/_search",
- },
- {
- []string{"index1", "index2"},
- []string{},
- "/index1%2Cindex2/_search",
- },
- {
- []string{},
- []string{"type1"},
- "/_all/type1/_search",
- },
- {
- []string{"index1"},
- []string{"type1"},
- "/index1/type1/_search",
- },
- {
- []string{"index1", "index2"},
- []string{"type1", "type2"},
- "/index1%2Cindex2/type1%2Ctype2/_search",
- },
- {
- []string{},
- []string{"type1", "type2"},
- "/_all/type1%2Ctype2/_search",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.Search().Index(test.Indices...).Type(test.Types...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestSearchFilterPath(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
- client := setupTestClientAndCreateIndexAndAddDocs(t)
-
- // Match all should return all documents
- all := NewMatchAllQuery()
- searchResult, err := client.Search().
- Index(testIndexName).
- Type("doc").
- Query(all).
- FilterPath(
- "took",
- "hits.hits._id",
- "hits.hits._source.user",
- "hits.hits._source.message",
- ).
- Timeout("1s").
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Fatalf("expected SearchResult.Hits != nil; got nil")
- }
- // 0 because it was filtered out
- if want, got := int64(0), searchResult.Hits.TotalHits; want != got {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
- }
- if want, got := 3, len(searchResult.Hits.Hits); want != got {
- t.Fatalf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if want, got := "", hit.Index; want != got {
- t.Fatalf("expected index %q, got %q", want, got)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- // user field
- v, found := item["user"]
- if !found {
- t.Fatalf("expected SearchResult.Hits.Hit[%q] to be found", "user")
- }
- if v == "" {
- t.Fatalf("expected user field, got %v (%T)", v, v)
- }
- // No retweets field
- v, found = item["retweets"]
- if found {
- t.Fatalf("expected SearchResult.Hits.Hit[%q] to not be found, got %v", "retweets", v)
- }
- if v == "" {
- t.Fatalf("expected user field, got %v (%T)", v, v)
- }
- }
-}
-
-func TestSearchAfter(t *testing.T) {
- // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0)))
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{
- User: "olivere", Retweets: 108,
- Message: "Welcome to Golang and Elasticsearch.",
- Created: time.Date(2012, 12, 12, 17, 38, 34, 0, time.UTC),
- }
- tweet2 := tweet{
- User: "olivere", Retweets: 0,
- Message: "Another unrelated topic.",
- Created: time.Date(2012, 10, 10, 8, 12, 03, 0, time.UTC),
- }
- tweet3 := tweet{
- User: "sandrae", Retweets: 12,
- Message: "Cycling is fun.",
- Created: time.Date(2011, 11, 11, 10, 58, 12, 0, time.UTC),
- }
-
- // Add all documents
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = client.Flush().Index(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Query(NewMatchAllQuery()).
- SearchAfter("olivere").
- Sort("user", true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if searchResult.Hits == nil {
- t.Errorf("expected SearchResult.Hits != nil; got nil")
- }
- if searchResult.Hits.TotalHits != 3 {
- t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 3, searchResult.Hits.TotalHits)
- }
- if want, got := 1, len(searchResult.Hits.Hits); want != got {
- t.Fatalf("expected len(SearchResult.Hits.Hits) = %d; got: %d", want, got)
- }
- hit := searchResult.Hits.Hits[0]
- if want, got := "3", hit.Id; want != got {
- t.Fatalf("expected tweet %q; got: %q", want, got)
- }
-}
-
-func TestSearchResultWithFieldCollapsing(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Type("doc").
- Query(NewMatchAllQuery()).
- Collapse(NewCollapseBuilder("user")).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- if searchResult.Hits == nil {
- t.Fatalf("expected SearchResult.Hits != nil; got nil")
- }
- if got := searchResult.Hits.TotalHits; got == 0 {
- t.Fatalf("expected SearchResult.Hits.TotalHits > 0; got %d", got)
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- if len(hit.Fields) == 0 {
- t.Fatal("expected fields in SearchResult")
- }
- usersVal, ok := hit.Fields["user"]
- if !ok {
- t.Fatalf("expected %q field in fields of SearchResult", "user")
- }
- users, ok := usersVal.([]interface{})
- if !ok {
- t.Fatalf("expected slice of strings in field of SearchResult, got %T", usersVal)
- }
- if len(users) != 1 {
- t.Fatalf("expected 1 entry in users slice, got %d", len(users))
- }
- }
-}
-
-func TestSearchResultWithFieldCollapsingAndInnerHits(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- searchResult, err := client.Search().
- Index(testIndexName).
- Type("doc").
- Query(NewMatchAllQuery()).
- Collapse(
- NewCollapseBuilder("user").
- InnerHit(
- NewInnerHit().Name("last_tweets").Size(5).Sort("created", true),
- ).
- MaxConcurrentGroupRequests(4)).
- Pretty(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- if searchResult.Hits == nil {
- t.Fatalf("expected SearchResult.Hits != nil; got nil")
- }
- if got := searchResult.Hits.TotalHits; got == 0 {
- t.Fatalf("expected SearchResult.Hits.TotalHits > 0; got %d", got)
- }
-
- for _, hit := range searchResult.Hits.Hits {
- if hit.Index != testIndexName {
- t.Fatalf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
- }
- item := make(map[string]interface{})
- err := json.Unmarshal(*hit.Source, &item)
- if err != nil {
- t.Fatal(err)
- }
- if len(hit.Fields) == 0 {
- t.Fatal("expected fields in SearchResult")
- }
- usersVal, ok := hit.Fields["user"]
- if !ok {
- t.Fatalf("expected %q field in fields of SearchResult", "user")
- }
- users, ok := usersVal.([]interface{})
- if !ok {
- t.Fatalf("expected slice of strings in field of SearchResult, got %T", usersVal)
- }
- if len(users) != 1 {
- t.Fatalf("expected 1 entry in users slice, got %d", len(users))
- }
- lastTweets, ok := hit.InnerHits["last_tweets"]
- if !ok {
- t.Fatalf("expected inner_hits named %q in SearchResult", "last_tweets")
- }
- if lastTweets == nil {
- t.Fatal("expected inner_hits in SearchResult")
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/setup_test.go b/vendor/gopkg.in/olivere/elastic.v5/setup_test.go
deleted file mode 100644
index 480ae5d20..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/setup_test.go
+++ /dev/null
@@ -1,445 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "fmt"
- "log"
- "math/rand"
- "os"
- "time"
-)
-
-const (
- testIndexName = "elastic-test"
- testIndexName2 = "elastic-test2"
- testIndexName3 = "elastic-test3"
- testMapping = `
-{
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "user":{
- "type":"keyword"
- },
- "message":{
- "type":"text",
- "store": true,
- "fielddata": true
- },
- "tags":{
- "type":"keyword"
- },
- "location":{
- "type":"geo_point"
- },
- "suggest_field":{
- "type":"completion",
- "contexts":[
- {
- "name":"user_name",
- "type":"category"
- }
- ]
- }
- }
- }
- }
-}
-`
-
- testNoSourceIndexName = "elastic-nosource-test"
- testNoSourceMapping = `
-{
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "_source": {
- "enabled": false
- },
- "properties":{
- "user":{
- "type":"keyword"
- },
- "message":{
- "type":"text",
- "store": true,
- "fielddata": true
- },
- "tags":{
- "type":"keyword"
- },
- "location":{
- "type":"geo_point"
- },
- "suggest_field":{
- "type":"completion",
- "contexts":[
- {
- "name":"user_name",
- "type":"category"
- }
- ]
- }
- }
- }
- }
-}
-`
-
- testJoinIndex = "elastic-joins"
- testJoinMapping = `
- {
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "message":{
- "type":"text"
- },
- "my_join_field": {
- "type": "join",
- "relations": {
- "question": "answer"
- }
- }
- }
- }
- }
- }
-`
-
- testOrderIndex = "elastic-orders"
- testOrderMapping = `
-{
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "article":{
- "type":"text"
- },
- "manufacturer":{
- "type":"keyword"
- },
- "price":{
- "type":"float"
- },
- "time":{
- "type":"date",
- "format": "YYYY-MM-dd"
- }
- }
- }
- }
-}
-`
-
- /*
- testDoctypeIndex = "elastic-doctypes"
- testDoctypeMapping = `
- {
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "message":{
- "type":"text",
- "store": true,
- "fielddata": true
- }
- }
- }
- }
- }
- `
- */
-
- testQueryIndex = "elastic-queries"
- testQueryMapping = `
-{
- "settings":{
- "number_of_shards":1,
- "number_of_replicas":0
- },
- "mappings":{
- "doc":{
- "properties":{
- "message":{
- "type":"text",
- "store": true,
- "fielddata": true
- },
- "query": {
- "type": "percolator"
- }
- }
- }
- }
-}
-`
-)
-
-type tweet struct {
- User string `json:"user"`
- Message string `json:"message"`
- Retweets int `json:"retweets"`
- Image string `json:"image,omitempty"`
- Created time.Time `json:"created,omitempty"`
- Tags []string `json:"tags,omitempty"`
- Location string `json:"location,omitempty"`
- Suggest *SuggestField `json:"suggest_field,omitempty"`
-}
-
-func (t tweet) String() string {
- return fmt.Sprintf("tweet{User:%q,Message:%q,Retweets:%d}", t.User, t.Message, t.Retweets)
-}
-
-type comment struct {
- User string `json:"user"`
- Comment string `json:"comment"`
- Created time.Time `json:"created,omitempty"`
-}
-
-func (c comment) String() string {
- return fmt.Sprintf("comment{User:%q,Comment:%q}", c.User, c.Comment)
-}
-
-type joinDoc struct {
- Message string `json:"message"`
- JoinField interface{} `json:"my_join_field,omitempty"`
-}
-
-type joinField struct {
- Name string `json:"name"`
- Parent string `json:"parent,omitempty"`
-}
-
-type order struct {
- Article string `json:"article"`
- Manufacturer string `json:"manufacturer"`
- Price float64 `json:"price"`
- Time string `json:"time,omitempty"`
-}
-
-func (o order) String() string {
- return fmt.Sprintf("order{Article:%q,Manufacturer:%q,Price:%v,Time:%v}", o.Article, o.Manufacturer, o.Price, o.Time)
-}
-
-// doctype is required for Percolate tests.
-type doctype struct {
- Message string `json:"message"`
-}
-
-// queries is required for Percolate tests.
-type queries struct {
- Query string `json:"query"`
-}
-
-func isTravis() bool {
- return os.Getenv("TRAVIS") != ""
-}
-
-func travisGoVersion() string {
- return os.Getenv("TRAVIS_GO_VERSION")
-}
-
-type logger interface {
- Error(args ...interface{})
- Errorf(format string, args ...interface{})
- Fatal(args ...interface{})
- Fatalf(format string, args ...interface{})
- Fail()
- FailNow()
- Log(args ...interface{})
- Logf(format string, args ...interface{})
-}
-
-func setupTestClient(t logger, options ...ClientOptionFunc) (client *Client) {
- var err error
-
- client, err = NewClient(options...)
- if err != nil {
- t.Fatal(err)
- }
-
- client.DeleteIndex(testIndexName).Do(context.TODO())
- client.DeleteIndex(testIndexName2).Do(context.TODO())
- client.DeleteIndex(testIndexName3).Do(context.TODO())
- client.DeleteIndex(testOrderIndex).Do(context.TODO())
- client.DeleteIndex(testNoSourceIndexName).Do(context.TODO())
- //client.DeleteIndex(testDoctypeIndex).Do(context.TODO())
- client.DeleteIndex(testQueryIndex).Do(context.TODO())
- client.DeleteIndex(testJoinIndex).Do(context.TODO())
-
- return client
-}
-
-func setupTestClientAndCreateIndex(t logger, options ...ClientOptionFunc) *Client {
- client := setupTestClient(t, options...)
-
- // Create index
- createIndex, err := client.CreateIndex(testIndexName).Body(testMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex)
- }
-
- // Create second index
- createIndex2, err := client.CreateIndex(testIndexName2).Body(testMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createIndex2 == nil {
- t.Errorf("expected result to be != nil; got: %v", createIndex2)
- }
-
- // Create no source index
- createNoSourceIndex, err := client.CreateIndex(testNoSourceIndexName).Body(testNoSourceMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createNoSourceIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createNoSourceIndex)
- }
-
- // Create order index
- createOrderIndex, err := client.CreateIndex(testOrderIndex).Body(testOrderMapping).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if createOrderIndex == nil {
- t.Errorf("expected result to be != nil; got: %v", createOrderIndex)
- }
-
- return client
-}
-
-func setupTestClientAndCreateIndexAndLog(t logger, options ...ClientOptionFunc) *Client {
- return setupTestClientAndCreateIndex(t, SetTraceLog(log.New(os.Stdout, "", 0)))
-}
-
-func setupTestClientAndCreateIndexAndAddDocs(t logger, options ...ClientOptionFunc) *Client {
- client := setupTestClientAndCreateIndex(t, options...)
-
- // Add tweets
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
- tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
- //comment1 := comment{User: "nico", Comment: "You bet."}
-
- _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Index().Index(testIndexName).Type("doc").Id("3").Routing("someroutingkey").BodyJson(&tweet3).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- /*
- _, err = client.Index().Index(testIndexName).Type("comment").Id("1").Parent("3").BodyJson(&comment1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- */
-
- // Add orders
- var orders []order
- orders = append(orders, order{Article: "Apple MacBook", Manufacturer: "Apple", Price: 1290, Time: "2015-01-18"})
- orders = append(orders, order{Article: "Paper", Manufacturer: "Canon", Price: 100, Time: "2015-03-01"})
- orders = append(orders, order{Article: "Apple iPad", Manufacturer: "Apple", Price: 499, Time: "2015-04-12"})
- orders = append(orders, order{Article: "Dell XPS 13", Manufacturer: "Dell", Price: 1600, Time: "2015-04-18"})
- orders = append(orders, order{Article: "Apple Watch", Manufacturer: "Apple", Price: 349, Time: "2015-04-29"})
- orders = append(orders, order{Article: "Samsung TV", Manufacturer: "Samsung", Price: 790, Time: "2015-05-03"})
- orders = append(orders, order{Article: "Hoodie", Manufacturer: "h&m", Price: 49, Time: "2015-06-03"})
- orders = append(orders, order{Article: "T-Shirt", Manufacturer: "h&m", Price: 19, Time: "2015-06-18"})
- for i, o := range orders {
- id := fmt.Sprintf("%d", i)
- _, err = client.Index().Index(testOrderIndex).Type("doc").Id(id).BodyJson(&o).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- }
-
- // Flush
- _, err = client.Flush().Index(testIndexName, testOrderIndex).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- return client
-}
-
-func setupTestClientAndCreateIndexAndAddDocsNoSource(t logger, options ...ClientOptionFunc) *Client {
- client := setupTestClientAndCreateIndex(t, options...)
-
- // Add tweets
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
- tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
-
- _, err := client.Index().Index(testNoSourceIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- _, err = client.Index().Index(testNoSourceIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- // Flush
- _, err = client.Flush().Index(testNoSourceIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
-
- return client
-}
-
-var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
-
-func randomString(n int) string {
- b := make([]rune, n)
- for i := range b {
- b[i] = letters[rand.Intn(len(letters))]
- }
- return string(b)
-}
-
-type lexicographically struct {
- strings []string
-}
-
-func (l lexicographically) Len() int {
- return len(l.strings)
-}
-
-func (l lexicographically) Less(i, j int) bool {
- return l.strings[i] < l.strings[j]
-}
-
-func (l lexicographically) Swap(i, j int) {
- l.strings[i], l.strings[j] = l.strings[j], l.strings[i]
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create.go
index 1bbd2762e..245fdbff8 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create.go
@@ -11,10 +11,10 @@ import (
"net/url"
"time"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
-// SnapshotCreateService is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-snapshots.html.
+// SnapshotCreateService is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/modules-snapshots.html.
type SnapshotCreateService struct {
client *Client
pretty bool
@@ -89,7 +89,7 @@ func (s *SnapshotCreateService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -137,12 +137,7 @@ func (s *SnapshotCreateService) Do(ctx context.Context) (*SnapshotCreateResponse
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository.go
index e7f6d5336..9fc0a32a6 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository.go
@@ -10,11 +10,11 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// SnapshotCreateRepositoryService creates a snapshot repository.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-snapshots.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/modules-snapshots.html
// for details.
type SnapshotCreateRepositoryService struct {
client *Client
@@ -112,7 +112,7 @@ func (s *SnapshotCreateRepositoryService) buildURL() (string, url.Values, error)
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -179,12 +179,7 @@ func (s *SnapshotCreateRepositoryService) Do(ctx context.Context) (*SnapshotCrea
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "PUT",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "PUT", path, params, body)
if err != nil {
return nil, err
}
@@ -199,7 +194,5 @@ func (s *SnapshotCreateRepositoryService) Do(ctx context.Context) (*SnapshotCrea
// SnapshotCreateRepositoryResponse is the response of SnapshotCreateRepositoryService.Do.
type SnapshotCreateRepositoryResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository_test.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository_test.go
deleted file mode 100644
index 2045c700d..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_repository_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSnapshotPutRepositoryURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Repository string
- Expected string
- }{
- {
- "repo",
- "/_snapshot/repo",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.SnapshotCreateRepository(test.Repository).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestSnapshotPutRepositoryBody(t *testing.T) {
- client := setupTestClient(t)
-
- service := client.SnapshotCreateRepository("my_backup")
- service = service.Type("fs").
- Settings(map[string]interface{}{
- "location": "my_backup_location",
- "compress": false,
- }).
- Setting("compress", true).
- Setting("chunk_size", 16*1024*1024)
-
- src, err := service.buildBody()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"settings":{"chunk_size":16777216,"compress":true,"location":"my_backup_location"},"type":"fs"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_test.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_test.go
deleted file mode 100644
index 74b009cfe..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_create_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package elastic
-
-import (
- "net/url"
- "reflect"
- "testing"
-)
-
-func TestSnapshotValidate(t *testing.T) {
- var client *Client
-
- err := NewSnapshotCreateService(client).Validate()
- got := err.Error()
- expected := "missing required fields: [Repository Snapshot]"
- if got != expected {
- t.Errorf("expected %q; got: %q", expected, got)
- }
-}
-
-func TestSnapshotPutURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Repository string
- Snapshot string
- Pretty bool
- MasterTimeout string
- WaitForCompletion bool
- ExpectedPath string
- ExpectedParams url.Values
- }{
- {
- Repository: "repo",
- Snapshot: "snapshot_of_sunday",
- Pretty: true,
- MasterTimeout: "60s",
- WaitForCompletion: true,
- ExpectedPath: "/_snapshot/repo/snapshot_of_sunday",
- ExpectedParams: url.Values{
- "pretty": []string{"true"},
- "master_timeout": []string{"60s"},
- "wait_for_completion": []string{"true"},
- },
- },
- }
-
- for _, test := range tests {
- path, params, err := client.SnapshotCreate(test.Repository, test.Snapshot).
- Pretty(test.Pretty).
- MasterTimeout(test.MasterTimeout).
- WaitForCompletion(test.WaitForCompletion).
- buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.ExpectedPath {
- t.Errorf("expected %q; got: %q", test.ExpectedPath, path)
- }
- if !reflect.DeepEqual(params, test.ExpectedParams) {
- t.Errorf("expected %q; got: %q", test.ExpectedParams, params)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository.go
index ad3e49b0e..1f402fba5 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository.go
@@ -11,11 +11,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// SnapshotDeleteRepositoryService deletes a snapshot repository.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-snapshots.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/modules-snapshots.html
// for details.
type SnapshotDeleteRepositoryService struct {
client *Client
@@ -70,7 +70,7 @@ func (s *SnapshotDeleteRepositoryService) buildURL() (string, url.Values, error)
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -107,11 +107,7 @@ func (s *SnapshotDeleteRepositoryService) Do(ctx context.Context) (*SnapshotDele
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "DELETE",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "DELETE", path, params, nil)
if err != nil {
return nil, err
}
@@ -126,7 +122,5 @@ func (s *SnapshotDeleteRepositoryService) Do(ctx context.Context) (*SnapshotDele
// SnapshotDeleteRepositoryResponse is the response of SnapshotDeleteRepositoryService.Do.
type SnapshotDeleteRepositoryResponse struct {
- Acknowledged bool `json:"acknowledged"`
- ShardsAcknowledged bool `json:"shards_acknowledged"`
- Index string `json:"index,omitempty"`
+ Acknowledged bool `json:"acknowledged"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository_test.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository_test.go
deleted file mode 100644
index aec793a60..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_delete_repository_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestSnapshotDeleteRepositoryURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Repository []string
- Expected string
- }{
- {
- []string{"repo1"},
- "/_snapshot/repo1",
- },
- {
- []string{"repo1", "repo2"},
- "/_snapshot/repo1%2Crepo2",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.SnapshotDeleteRepository(test.Repository...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository.go
index 2d24c5e4c..10b2d0b9c 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository.go
@@ -11,11 +11,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// SnapshotGetRepositoryService reads a snapshot repository.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-snapshots.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/modules-snapshots.html
// for details.
type SnapshotGetRepositoryService struct {
client *Client
@@ -76,7 +76,7 @@ func (s *SnapshotGetRepositoryService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.local != nil {
params.Set("local", fmt.Sprintf("%v", *s.local))
@@ -106,11 +106,7 @@ func (s *SnapshotGetRepositoryService) Do(ctx context.Context) (SnapshotGetRepos
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository_test.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository_test.go
deleted file mode 100644
index 0dcd0bb90..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_get_repository_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestSnapshotGetRepositoryURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Repository []string
- Expected string
- }{
- {
- []string{},
- "/_snapshot",
- },
- {
- []string{"repo1"},
- "/_snapshot/repo1",
- },
- {
- []string{"repo1", "repo2"},
- "/_snapshot/repo1%2Crepo2",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.SnapshotGetRepository(test.Repository...).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository.go
index 5494ab475..4e8c25a24 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository.go
@@ -10,11 +10,11 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// SnapshotVerifyRepositoryService verifies a snapshop repository.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-snapshots.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/modules-snapshots.html
// for details.
type SnapshotVerifyRepositoryService struct {
client *Client
@@ -68,7 +68,7 @@ func (s *SnapshotVerifyRepositoryService) buildURL() (string, url.Values, error)
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
@@ -105,11 +105,7 @@ func (s *SnapshotVerifyRepositoryService) Do(ctx context.Context) (*SnapshotVeri
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository_test.go b/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository_test.go
deleted file mode 100644
index 9776782d2..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/snapshot_verify_repository_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestSnapshotVerifyRepositoryURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Repository string
- Expected string
- }{
- {
- "repo",
- "/_snapshot/repo/_verify",
- },
- }
-
- for _, test := range tests {
- path, _, err := client.SnapshotVerifyRepository(test.Repository).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/sort.go b/vendor/gopkg.in/olivere/elastic.v5/sort.go
index 7e2b32183..fddbbb610 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/sort.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/sort.go
@@ -9,7 +9,7 @@ import "errors"
// -- Sorter --
// Sorter is an interface for sorting strategies, e.g. ScoreSort or FieldSort.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-sort.html.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-sort.html.
type Sorter interface {
Source() (interface{}, error)
}
@@ -27,7 +27,6 @@ type SortInfo struct {
SortMode string
NestedFilter Query
NestedPath string
- NestedSort *NestedSort // available in 6.1 or later
}
func (info SortInfo) Source() (interface{}, error) {
@@ -59,13 +58,6 @@ func (info SortInfo) Source() (interface{}, error) {
if info.NestedPath != "" {
prop["nested_path"] = info.NestedPath
}
- if info.NestedSort != nil {
- src, err := info.NestedSort.Source()
- if err != nil {
- return nil, err
- }
- prop["nested"] = src
- }
source := make(map[string]interface{})
source[info.Field] = prop
return source, nil
@@ -74,7 +66,7 @@ func (info SortInfo) Source() (interface{}, error) {
// -- SortByDoc --
// SortByDoc sorts by the "_doc" field, as described in
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-scroll.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-scroll.html.
//
// Example:
// ss := elastic.NewSearchSource()
@@ -144,7 +136,6 @@ type FieldSort struct {
sortMode *string
nestedFilter Query
nestedPath *string
- nestedSort *NestedSort
}
// NewFieldSort creates a new FieldSort.
@@ -216,13 +207,6 @@ func (s *FieldSort) NestedPath(nestedPath string) *FieldSort {
return s
}
-// NestedSort is available starting with 6.1 and will replace NestedFilter
-// and NestedPath.
-func (s *FieldSort) NestedSort(nestedSort *NestedSort) *FieldSort {
- s.nestedSort = nestedSort
- return s
-}
-
// Source returns the JSON-serializable data.
func (s *FieldSort) Source() (interface{}, error) {
source := make(map[string]interface{})
@@ -252,20 +236,13 @@ func (s *FieldSort) Source() (interface{}, error) {
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
}
// -- GeoDistanceSort --
// GeoDistanceSort allows for sorting by geographic distance.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-sort.html#_geo_distance_sorting.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-sort.html#_geo_distance_sorting.
type GeoDistanceSort struct {
Sorter
fieldName string
@@ -277,7 +254,6 @@ type GeoDistanceSort struct {
sortMode *string
nestedFilter Query
nestedPath *string
- nestedSort *NestedSort
}
// NewGeoDistanceSort creates a new sorter for geo distances.
@@ -331,7 +307,7 @@ func (s *GeoDistanceSort) GeoHashes(geohashes ...string) *GeoDistanceSort {
}
// Unit specifies the distance unit to use. It defaults to km.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/common-options.html#distance-units
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/common-options.html#distance-units
// for details.
func (s *GeoDistanceSort) Unit(unit string) *GeoDistanceSort {
s.unit = unit
@@ -344,7 +320,7 @@ func (s *GeoDistanceSort) GeoDistance(geoDistance string) *GeoDistanceSort {
}
// DistanceType describes how to compute the distance, e.g. "arc" or "plane".
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-sort.html#geo-sorting
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-sort.html#geo-sorting
// for details.
func (s *GeoDistanceSort) DistanceType(distanceType string) *GeoDistanceSort {
s.distanceType = &distanceType
@@ -373,13 +349,6 @@ func (s *GeoDistanceSort) NestedPath(nestedPath string) *GeoDistanceSort {
return s
}
-// NestedSort is available starting with 6.1 and will replace NestedFilter
-// and NestedPath.
-func (s *GeoDistanceSort) NestedSort(nestedSort *NestedSort) *GeoDistanceSort {
- s.nestedSort = nestedSort
- return s
-}
-
// Source returns the JSON-serializable data.
func (s *GeoDistanceSort) Source() (interface{}, error) {
source := make(map[string]interface{})
@@ -421,20 +390,13 @@ func (s *GeoDistanceSort) Source() (interface{}, error) {
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
}
// -- ScriptSort --
// ScriptSort sorts by a custom script. See
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/modules-scripting.html#modules-scripting
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/modules-scripting.html#modules-scripting
// for details about scripting.
type ScriptSort struct {
Sorter
@@ -444,7 +406,6 @@ type ScriptSort struct {
sortMode *string
nestedFilter Query
nestedPath *string
- nestedSort *NestedSort
}
// NewScriptSort creates and initializes a new ScriptSort.
@@ -503,13 +464,6 @@ func (s *ScriptSort) NestedPath(nestedPath string) *ScriptSort {
return s
}
-// NestedSort is available starting with 6.1 and will replace NestedFilter
-// and NestedPath.
-func (s *ScriptSort) NestedSort(nestedSort *NestedSort) *ScriptSort {
- s.nestedSort = nestedSort
- return s
-}
-
// Source returns the JSON-serializable data.
func (s *ScriptSort) Source() (interface{}, error) {
if s.script == nil {
@@ -545,70 +499,5 @@ func (s *ScriptSort) Source() (interface{}, error) {
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
-}
-
-// -- NestedSort --
-
-// NestedSort is used for fields that are inside a nested object.
-// It takes a "path" argument and an optional nested filter that the
-// nested objects should match with in order to be taken into account
-// for sorting.
-//
-// NestedSort is available from 6.1 and replaces nestedFilter and nestedPath
-// in the other sorters.
-type NestedSort struct {
- Sorter
- path string
- filter Query
- nestedSort *NestedSort
-}
-
-// NewNestedSort creates a new NestedSort.
-func NewNestedSort(path string) *NestedSort {
- return &NestedSort{path: path}
-}
-
-// Filter sets the filter.
-func (s *NestedSort) Filter(filter Query) *NestedSort {
- s.filter = filter
- return s
-}
-
-// NestedSort embeds another level of nested sorting.
-func (s *NestedSort) NestedSort(nestedSort *NestedSort) *NestedSort {
- s.nestedSort = nestedSort
- return s
-}
-
-// Source returns the JSON-serializable data.
-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
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/sort_test.go b/vendor/gopkg.in/olivere/elastic.v5/sort_test.go
deleted file mode 100644
index b54cbd98c..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/sort_test.go
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSortInfo(t *testing.T) {
- builder := SortInfo{Field: "grade", Ascending: false}
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"grade":{"order":"desc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSortInfoComplex(t *testing.T) {
- builder := SortInfo{
- Field: "price",
- Ascending: false,
- Missing: "_last",
- SortMode: "avg",
- NestedFilter: NewTermQuery("product.color", "blue"),
- NestedPath: "variant",
- }
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"price":{"missing":"_last","mode":"avg","nested_filter":{"term":{"product.color":"blue"}},"nested_path":"variant","order":"desc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScoreSort(t *testing.T) {
- builder := NewScoreSort()
- if builder.ascending != false {
- t.Error("expected score sorter to be ascending by default")
- }
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_score":{"order":"desc"}}` // ScoreSort is "desc" by default
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScoreSortOrderAscending(t *testing.T) {
- builder := NewScoreSort().Asc()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_score":{"order":"asc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScoreSortOrderDescending(t *testing.T) {
- builder := NewScoreSort().Desc()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_score":{"order":"desc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldSort(t *testing.T) {
- builder := NewFieldSort("grade")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"grade":{"order":"asc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldSortOrderDesc(t *testing.T) {
- builder := NewFieldSort("grade").Desc()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"grade":{"order":"desc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldSortComplex(t *testing.T) {
- builder := NewFieldSort("price").Desc().
- SortMode("avg").
- Missing("_last").
- UnmappedType("product").
- NestedFilter(NewTermQuery("product.color", "blue")).
- NestedPath("variant")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"price":{"missing":"_last","mode":"avg","nested_filter":{"term":{"product.color":"blue"}},"nested_path":"variant","order":"desc","unmapped_type":"product"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceSort(t *testing.T) {
- builder := NewGeoDistanceSort("pin.location").
- Point(-70, 40).
- Order(true).
- Unit("km").
- SortMode("min").
- GeoDistance("plane")
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_geo_distance":{"distance_type":"plane","mode":"min","order":"asc","pin.location":[{"lat":-70,"lon":40}],"unit":"km"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestGeoDistanceSortOrderDesc(t *testing.T) {
- builder := NewGeoDistanceSort("pin.location").
- Point(-70, 40).
- Unit("km").
- SortMode("min").
- GeoDistance("arc").
- Desc()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_geo_distance":{"distance_type":"arc","mode":"min","order":"desc","pin.location":[{"lat":-70,"lon":40}],"unit":"km"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-func TestScriptSort(t *testing.T) {
- builder := NewScriptSort(NewScript("doc['field_name'].value * factor").Param("factor", 1.1), "number").Order(true)
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_script":{"order":"asc","script":{"params":{"factor":1.1},"source":"doc['field_name'].value * factor"},"type":"number"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestScriptSortOrderDesc(t *testing.T) {
- builder := NewScriptSort(NewScript("doc['field_name'].value * factor").Param("factor", 1.1), "number").Desc()
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"_script":{"order":"desc","script":{"params":{"factor":1.1},"source":"doc['field_name'].value * factor"},"type":"number"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestNestedSort(t *testing.T) {
- builder := NewNestedSort("offer").
- Filter(NewTermQuery("offer.color", "blue"))
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"filter":{"term":{"offer.color":"blue"}},"path":"offer"}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestFieldSortWithNestedSort(t *testing.T) {
- builder := NewFieldSort("offer.price").
- Asc().
- SortMode("avg").
- NestedSort(
- NewNestedSort("offer").Filter(NewTermQuery("offer.color", "blue")),
- )
- src, err := builder.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"offer.price":{"mode":"avg","nested":{"filter":{"term":{"offer.color":"blue"}},"path":"offer"},"order":"asc"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggest.go b/vendor/gopkg.in/olivere/elastic.v5/suggest.go
new file mode 100644
index 000000000..7249abd5f
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggest.go
@@ -0,0 +1,158 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// SuggestService returns suggestions for text.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters.html.
+type SuggestService struct {
+ client *Client
+ pretty bool
+ routing string
+ preference string
+ index []string
+ suggesters []Suggester
+}
+
+// NewSuggestService creates a new instance of SuggestService.
+func NewSuggestService(client *Client) *SuggestService {
+ builder := &SuggestService{
+ client: client,
+ }
+ return builder
+}
+
+// Index adds one or more indices to use for the suggestion request.
+func (s *SuggestService) Index(index ...string) *SuggestService {
+ s.index = append(s.index, index...)
+ return s
+}
+
+// Pretty asks Elasticsearch to return indented JSON.
+func (s *SuggestService) Pretty(pretty bool) *SuggestService {
+ s.pretty = pretty
+ return s
+}
+
+// Routing specifies the routing value.
+func (s *SuggestService) Routing(routing string) *SuggestService {
+ s.routing = routing
+ return s
+}
+
+// Preference specifies the node or shard the operation should be
+// performed on (default: random).
+func (s *SuggestService) Preference(preference string) *SuggestService {
+ s.preference = preference
+ return s
+}
+
+// Suggester adds a suggester to the request.
+func (s *SuggestService) Suggester(suggester Suggester) *SuggestService {
+ s.suggesters = append(s.suggesters, suggester)
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *SuggestService) buildURL() (string, url.Values, error) {
+ var err error
+ var path string
+
+ if len(s.index) > 0 {
+ path, err = uritemplates.Expand("/{index}/_suggest", map[string]string{
+ "index": strings.Join(s.index, ","),
+ })
+ } else {
+ path = "/_suggest"
+ }
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.pretty {
+ params.Set("pretty", fmt.Sprintf("%v", s.pretty))
+ }
+ if s.routing != "" {
+ params.Set("routing", s.routing)
+ }
+ if s.preference != "" {
+ params.Set("preference", s.preference)
+ }
+ return path, params, nil
+}
+
+// Do executes the request.
+func (s *SuggestService) Do(ctx context.Context) (SuggestResult, error) {
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Set body
+ body := make(map[string]interface{})
+ for _, s := range s.suggesters {
+ src, err := s.Source(false)
+ if err != nil {
+ return nil, err
+ }
+ body[s.Name()] = src
+ }
+
+ // Get response
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
+ if err != nil {
+ return nil, err
+ }
+
+ // There is a _shard object that cannot be deserialized.
+ // So we use json.RawMessage instead.
+ var suggestions map[string]*json.RawMessage
+ if err := s.client.decoder.Decode(res.Body, &suggestions); err != nil {
+ return nil, err
+ }
+
+ ret := make(SuggestResult)
+ for name, result := range suggestions {
+ if name != "_shards" {
+ var sug []Suggestion
+ if err := s.client.decoder.Decode(*result, &sug); err != nil {
+ return nil, err
+ }
+ ret[name] = sug
+ }
+ }
+
+ return ret, nil
+}
+
+// SuggestResult is the outcome of SuggestService.Do.
+type SuggestResult map[string][]Suggestion
+
+// Suggestion is a single suggester outcome.
+type Suggestion struct {
+ Text string `json:"text"`
+ Offset int `json:"offset"`
+ Length int `json:"length"`
+ Options []suggestionOption `json:"options"`
+}
+
+type suggestionOption struct {
+ Text string `json:"text"`
+ Score float64 `json:"score"`
+ Freq int `json:"freq"`
+ Payload interface{} `json:"payload"`
+ CollateMatch bool `json:"collate_match"`
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggest_field.go b/vendor/gopkg.in/olivere/elastic.v5/suggest_field.go
index 8405a6f9e..8e15b4ec2 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggest_field.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggest_field.go
@@ -67,7 +67,7 @@ func (f *SuggestField) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- source["contexts"] = src
+ source["context"] = src
default:
ctxq := make(map[string]interface{})
for _, query := range f.contextQueries {
@@ -83,7 +83,7 @@ func (f *SuggestField) MarshalJSON() ([]byte, error) {
ctxq[k] = v
}
}
- source["contexts"] = ctxq
+ source["context"] = ctxq
}
return json.Marshal(source)
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggest_field_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggest_field_test.go
deleted file mode 100644
index 426875b2f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggest_field_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSuggestField(t *testing.T) {
- field := NewSuggestField().
- Input("Welcome to Golang and Elasticsearch.", "Golang and Elasticsearch").
- Weight(1).
- ContextQuery(
- NewSuggesterCategoryMapping("color").FieldName("color_field").DefaultValues("red", "green", "blue"),
- NewSuggesterGeoMapping("location").Precision("5m").Neighbors(true).DefaultLocations(GeoPointFromLatLon(52.516275, 13.377704)),
- )
- data, err := json.Marshal(field)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"contexts":{"color":{"default":["red","green","blue"],"path":"color_field","type":"category"},"location":{"default":{"lat":52.516275,"lon":13.377704},"neighbors":true,"precision":["5m"],"type":"geo"}},"input":["Welcome to Golang and Elasticsearch.","Golang and Elasticsearch"],"weight":1}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_completion.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_completion.go
index d2b4a326c..cf775c954 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_completion.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_completion.go
@@ -22,9 +22,8 @@ type CompletionSuggester struct {
contextQueries []SuggesterContextQuery
payload interface{}
- fuzzyOptions *FuzzyCompletionSuggesterOptions
- regexOptions *RegexCompletionSuggesterOptions
- skipDuplicates *bool
+ fuzzyOptions *FuzzyCompletionSuggesterOptions
+ regexOptions *RegexCompletionSuggesterOptions
}
// Creates a new completion suggester.
@@ -65,14 +64,6 @@ func (q *CompletionSuggester) FuzzyOptions(options *FuzzyCompletionSuggesterOpti
return q
}
-func (q *CompletionSuggester) Fuzziness(fuzziness interface{}) *CompletionSuggester {
- if q.fuzzyOptions == nil {
- q.fuzzyOptions = NewFuzzyCompletionSuggesterOptions()
- }
- q.fuzzyOptions = q.fuzzyOptions.EditDistance(fuzziness)
- return q
-}
-
func (q *CompletionSuggester) Regex(regex string) *CompletionSuggester {
q.regex = regex
return q
@@ -89,11 +80,6 @@ func (q *CompletionSuggester) RegexOptions(options *RegexCompletionSuggesterOpti
return q
}
-func (q *CompletionSuggester) SkipDuplicates(skipDuplicates bool) *CompletionSuggester {
- q.skipDuplicates = &skipDuplicates
- return q
-}
-
func (q *CompletionSuggester) Field(field string) *CompletionSuggester {
q.field = field
return q
@@ -171,7 +157,7 @@ func (q *CompletionSuggester) Source(includeName bool) (interface{}, error) {
if err != nil {
return nil, err
}
- suggester["contexts"] = src
+ suggester["context"] = src
default:
ctxq := make(map[string]interface{})
for _, query := range q.contextQueries {
@@ -209,10 +195,6 @@ func (q *CompletionSuggester) Source(includeName bool) (interface{}, error) {
suggester["regex"] = src
}
- if q.skipDuplicates != nil {
- suggester["skip_duplicates"] = *q.skipDuplicates
- }
-
// TODO(oe) Add completion-suggester specific parameters here
if !includeName {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_fuzzy.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_fuzzy.go
new file mode 100644
index 000000000..eccd1a020
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_fuzzy.go
@@ -0,0 +1,181 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+// FuzzyCompletionSuggester is a CompletionSuggester that allows fuzzy
+// completion.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-completion.html
+// for details, and
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-completion.html#fuzzy
+// for details about the fuzzy completion suggester.
+//
+// @Deprecated Use CompletionSuggester with FuzzyOptions instead.
+type FuzzyCompletionSuggester struct {
+ Suggester
+ name string
+ text string
+ field string
+ analyzer string
+ size *int
+ shardSize *int
+ contextQueries []SuggesterContextQuery
+
+ fuzziness interface{}
+ fuzzyTranspositions *bool
+ fuzzyMinLength *int
+ fuzzyPrefixLength *int
+ unicodeAware *bool
+}
+
+// Fuzziness defines the fuzziness which is used in FuzzyCompletionSuggester.
+type Fuzziness struct {
+}
+
+// Creates a new completion suggester.
+func NewFuzzyCompletionSuggester(name string) *FuzzyCompletionSuggester {
+ return &FuzzyCompletionSuggester{
+ name: name,
+ contextQueries: make([]SuggesterContextQuery, 0),
+ }
+}
+
+func (q *FuzzyCompletionSuggester) Name() string {
+ return q.name
+}
+
+func (q *FuzzyCompletionSuggester) Text(text string) *FuzzyCompletionSuggester {
+ q.text = text
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) Field(field string) *FuzzyCompletionSuggester {
+ q.field = field
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) Analyzer(analyzer string) *FuzzyCompletionSuggester {
+ q.analyzer = analyzer
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) Size(size int) *FuzzyCompletionSuggester {
+ q.size = &size
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) ShardSize(shardSize int) *FuzzyCompletionSuggester {
+ q.shardSize = &shardSize
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) ContextQuery(query SuggesterContextQuery) *FuzzyCompletionSuggester {
+ q.contextQueries = append(q.contextQueries, query)
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) ContextQueries(queries ...SuggesterContextQuery) *FuzzyCompletionSuggester {
+ q.contextQueries = append(q.contextQueries, queries...)
+ return q
+}
+
+// Fuzziness defines the strategy used to describe what "fuzzy" actually
+// means for the suggester, e.g. 1, 2, "0", "1..2", ">4", or "AUTO".
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/common-options.html#fuzziness
+// for a detailed description.
+func (q *FuzzyCompletionSuggester) Fuzziness(fuzziness interface{}) *FuzzyCompletionSuggester {
+ q.fuzziness = fuzziness
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) FuzzyTranspositions(fuzzyTranspositions bool) *FuzzyCompletionSuggester {
+ q.fuzzyTranspositions = &fuzzyTranspositions
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) FuzzyMinLength(minLength int) *FuzzyCompletionSuggester {
+ q.fuzzyMinLength = &minLength
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) FuzzyPrefixLength(prefixLength int) *FuzzyCompletionSuggester {
+ q.fuzzyPrefixLength = &prefixLength
+ return q
+}
+
+func (q *FuzzyCompletionSuggester) UnicodeAware(unicodeAware bool) *FuzzyCompletionSuggester {
+ q.unicodeAware = &unicodeAware
+ return q
+}
+
+// Creates the source for the completion suggester.
+func (q *FuzzyCompletionSuggester) Source(includeName bool) (interface{}, error) {
+ 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:
+ src, err := q.contextQueries[0].Source()
+ if err != nil {
+ return nil, err
+ }
+ suggester["context"] = src
+ default:
+ var ctxq []interface{}
+ for _, query := range q.contextQueries {
+ src, err := query.Source()
+ if err != nil {
+ return nil, err
+ }
+ ctxq = append(ctxq, src)
+ }
+ suggester["context"] = ctxq
+ }
+
+ // Fuzzy Completion Suggester fields
+ fuzzy := make(map[string]interface{})
+ suggester["fuzzy"] = fuzzy
+ if q.fuzziness != nil {
+ fuzzy["fuzziness"] = q.fuzziness
+ }
+ if q.fuzzyTranspositions != nil {
+ fuzzy["transpositions"] = *q.fuzzyTranspositions
+ }
+ if q.fuzzyMinLength != nil {
+ fuzzy["min_length"] = *q.fuzzyMinLength
+ }
+ if q.fuzzyPrefixLength != nil {
+ fuzzy["prefix_length"] = *q.fuzzyPrefixLength
+ }
+ if q.unicodeAware != nil {
+ fuzzy["unicode_aware"] = *q.unicodeAware
+ }
+
+ if !includeName {
+ return cs, nil
+ }
+
+ source := make(map[string]interface{})
+ source[q.name] = cs
+ return source, nil
+}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_test.go
deleted file mode 100644
index adbf58657..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_completion_test.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestCompletionSuggesterSource(t *testing.T) {
- s := NewCompletionSuggester("song-suggest").
- Text("n").
- Field("suggest")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"song-suggest":{"text":"n","completion":{"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompletionSuggesterPrefixSource(t *testing.T) {
- s := NewCompletionSuggester("song-suggest").
- Prefix("nir").
- Field("suggest")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"song-suggest":{"prefix":"nir","completion":{"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompletionSuggesterPrefixWithFuzzySource(t *testing.T) {
- s := NewCompletionSuggester("song-suggest").
- Prefix("nor").
- Field("suggest").
- FuzzyOptions(NewFuzzyCompletionSuggesterOptions().EditDistance(2))
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"song-suggest":{"prefix":"nor","completion":{"field":"suggest","fuzzy":{"fuzziness":2}}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompletionSuggesterRegexSource(t *testing.T) {
- s := NewCompletionSuggester("song-suggest").
- Regex("n[ever|i]r").
- Field("suggest")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"song-suggest":{"regex":"n[ever|i]r","completion":{"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestCompletionSuggesterSourceWithMultipleContexts(t *testing.T) {
- s := NewCompletionSuggester("song-suggest").
- Text("n").
- Field("suggest").
- ContextQueries(
- NewSuggesterCategoryQuery("artist", "Sting"),
- NewSuggesterCategoryQuery("label", "BMG"),
- )
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"song-suggest":{"text":"n","completion":{"contexts":{"artist":[{"context":"Sting"}],"label":[{"context":"BMG"}]},"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected %s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context.go
index 12877c1a6..ade099151 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_context.go
@@ -13,7 +13,7 @@ type SuggesterContextQuery interface {
}
// ContextSuggester is a fast suggester for e.g. type-ahead completion that supports filtering and boosting based on contexts.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/suggester-context.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/current/suggester-context.html
// for more details.
type ContextSuggester struct {
Suggester
@@ -94,7 +94,7 @@ func (q *ContextSuggester) Source(includeName bool) (interface{}, error) {
if err != nil {
return nil, err
}
- suggester["contexts"] = src
+ suggester["context"] = src
default:
ctxq := make(map[string]interface{})
for _, query := range q.contextQueries {
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category.go
index 9c50651fa..2d63fe8fb 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category.go
@@ -7,7 +7,7 @@ package elastic
// -- SuggesterCategoryMapping --
// SuggesterCategoryMapping provides a mapping for a category context in a suggester.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/suggester-context.html#_category_mapping.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/suggester-context.html#_category_mapping.
type SuggesterCategoryMapping struct {
name string
fieldName string
@@ -59,7 +59,7 @@ func (q *SuggesterCategoryMapping) Source() (interface{}, error) {
// -- SuggesterCategoryQuery --
// SuggesterCategoryQuery provides querying a category context in a suggester.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/suggester-context.html#_category_query.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/suggester-context.html#_category_query.
type SuggesterCategoryQuery struct {
name string
values map[string]*int
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category_test.go
deleted file mode 100644
index 46acd725e..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_category_test.go
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSuggesterCategoryMapping(t *testing.T) {
- q := NewSuggesterCategoryMapping("color").DefaultValues("red")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"color":{"default":"red","type":"category"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSuggesterCategoryMappingWithTwoDefaultValues(t *testing.T) {
- q := NewSuggesterCategoryMapping("color").DefaultValues("red", "orange")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"color":{"default":["red","orange"],"type":"category"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSuggesterCategoryMappingWithFieldName(t *testing.T) {
- q := NewSuggesterCategoryMapping("color").
- DefaultValues("red", "orange").
- FieldName("color_field")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"color":{"default":["red","orange"],"path":"color_field","type":"category"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSuggesterCategoryQuery(t *testing.T) {
- q := NewSuggesterCategoryQuery("color", "red")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"color":[{"context":"red"}]}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSuggesterCategoryQueryWithTwoValues(t *testing.T) {
- q := NewSuggesterCategoryQuery("color", "red", "yellow")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expectedOutcomes := []string{
- `{"color":[{"context":"red"},{"context":"yellow"}]}`,
- `{"color":[{"context":"yellow"},{"context":"red"}]}`,
- }
- var match bool
- for _, expected := range expectedOutcomes {
- if got == expected {
- match = true
- break
- }
- }
- if !match {
- t.Errorf("expected any of %v\n,got:\n%s", expectedOutcomes, got)
- }
-}
-
-func TestSuggesterCategoryQueryWithBoost(t *testing.T) {
- q := NewSuggesterCategoryQuery("color", "red")
- q.ValueWithBoost("yellow", 4)
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expectedOutcomes := []string{
- `{"color":[{"context":"red"},{"boost":4,"context":"yellow"}]}`,
- `{"color":[{"boost":4,"context":"yellow"},{"context":"red"}]}`,
- }
- var match bool
- for _, expected := range expectedOutcomes {
- if got == expected {
- match = true
- break
- }
- }
- if !match {
- t.Errorf("expected any of %v\n,got:\n%v", expectedOutcomes, got)
- }
-}
-
-func TestSuggesterCategoryQueryWithoutBoost(t *testing.T) {
- q := NewSuggesterCategoryQuery("color", "red")
- q.Value("yellow")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expectedOutcomes := []string{
- `{"color":[{"context":"red"},{"context":"yellow"}]}`,
- `{"color":[{"context":"yellow"},{"context":"red"}]}`,
- }
- var match bool
- for _, expected := range expectedOutcomes {
- if got == expected {
- match = true
- break
- }
- }
- if !match {
- t.Errorf("expected any of %v\n,got:\n%s", expectedOutcomes, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo.go
index 3fea63feb..6815bfe73 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo.go
@@ -7,7 +7,7 @@ package elastic
// -- SuggesterGeoMapping --
// SuggesterGeoMapping provides a mapping for a geolocation context in a suggester.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/suggester-context.html#_geo_location_mapping.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/suggester-context.html#_geo_location_mapping.
type SuggesterGeoMapping struct {
name string
defaultLocations []*GeoPoint
@@ -80,7 +80,7 @@ func (q *SuggesterGeoMapping) Source() (interface{}, error) {
// -- SuggesterGeoQuery --
// SuggesterGeoQuery provides querying a geolocation context in a suggester.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/suggester-context.html#_geo_location_query
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/suggester-context.html#_geo_location_query
type SuggesterGeoQuery struct {
name string
location *GeoPoint
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo_test.go
deleted file mode 100644
index b1ab2f495..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_geo_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestSuggesterGeoMapping(t *testing.T) {
- q := NewSuggesterGeoMapping("location").
- Precision("1km", "5m").
- Neighbors(true).
- FieldName("pin").
- DefaultLocations(GeoPointFromLatLon(0.0, 0.0))
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"location":{"default":{"lat":0,"lon":0},"neighbors":true,"path":"pin","precision":["1km","5m"],"type":"geo"}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestSuggesterGeoQuery(t *testing.T) {
- q := NewSuggesterGeoQuery("location", GeoPointFromLatLon(11.5, 62.71)).Precision("1km")
- src, err := q.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"location":{"precision":"1km","value":{"lat":11.5,"lon":62.71}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_context_test.go
deleted file mode 100644
index 045ccb2f4..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_context_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestContextSuggesterSource(t *testing.T) {
- s := NewContextSuggester("place_suggestion").
- Prefix("tim").
- Field("suggest")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"place_suggestion":{"prefix":"tim","completion":{"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestContextSuggesterSourceWithMultipleContexts(t *testing.T) {
- s := NewContextSuggester("place_suggestion").
- Prefix("tim").
- Field("suggest").
- ContextQueries(
- NewSuggesterCategoryQuery("place_type", "cafe", "restaurants"),
- )
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- // Due to the randomization of dictionary key, we could actually have two different valid expected outcomes
- expected := `{"place_suggestion":{"prefix":"tim","completion":{"contexts":{"place_type":[{"context":"cafe"},{"context":"restaurants"}]},"field":"suggest"}}}`
- if got != expected {
- expected := `{"place_suggestion":{"prefix":"tim","completion":{"contexts":{"place_type":[{"context":"restaurants"},{"context":"cafe"}]},"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected %s\n,got:\n%s", expected, got)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase.go
index 2f6b6a326..f75e1ddc1 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase.go
@@ -7,7 +7,7 @@ package elastic
// PhraseSuggester provides an API to access word alternatives
// on a per token basis within a certain string distance.
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-phrase.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-phrase.html.
type PhraseSuggester struct {
Suggester
name string
@@ -213,7 +213,7 @@ func (q *PhraseSuggester) Source(includeName bool) (interface{}, error) {
if err != nil {
return nil, err
}
- suggester["contexts"] = src
+ suggester["context"] = src
default:
var ctxq []interface{}
for _, query := range q.contextQueries {
@@ -223,7 +223,7 @@ func (q *PhraseSuggester) Source(includeName bool) (interface{}, error) {
}
ctxq = append(ctxq, src)
}
- suggester["contexts"] = ctxq
+ suggester["context"] = ctxq
}
// Phase-specified parameters
@@ -312,7 +312,7 @@ type SmoothingModel interface {
}
// StupidBackoffSmoothingModel implements a stupid backoff smoothing model.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-phrase.html#_smoothing_models
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-phrase.html#_smoothing_models
// for details about smoothing models.
type StupidBackoffSmoothingModel struct {
discount float64
@@ -337,7 +337,7 @@ func (sm *StupidBackoffSmoothingModel) Source() (interface{}, error) {
// --
// LaplaceSmoothingModel implements a laplace smoothing model.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-phrase.html#_smoothing_models
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-phrase.html#_smoothing_models
// for details about smoothing models.
type LaplaceSmoothingModel struct {
alpha float64
@@ -363,7 +363,7 @@ func (sm *LaplaceSmoothingModel) Source() (interface{}, error) {
// LinearInterpolationSmoothingModel implements a linear interpolation
// smoothing model.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-phrase.html#_smoothing_models
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-phrase.html#_smoothing_models
// for details about smoothing models.
type LinearInterpolationSmoothingModel struct {
trigramLamda float64
@@ -399,7 +399,7 @@ type CandidateGenerator interface {
}
// DirectCandidateGenerator implements a direct candidate generator.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-phrase.html#_smoothing_models
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-phrase.html#_smoothing_models
// for details about smoothing models.
type DirectCandidateGenerator struct {
field string
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase_test.go
deleted file mode 100644
index 63dde686e..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_phrase_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestPhraseSuggesterSource(t *testing.T) {
- s := NewPhraseSuggester("name").
- Text("Xor the Got-Jewel").
- Analyzer("body").
- Field("bigram").
- Size(1).
- RealWordErrorLikelihood(0.95).
- MaxErrors(0.5).
- GramSize(2).
- Highlight("<em>", "</em>")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"name":{"text":"Xor the Got-Jewel","phrase":{"analyzer":"body","field":"bigram","gram_size":2,"highlight":{"post_tag":"\u003c/em\u003e","pre_tag":"\u003cem\u003e"},"max_errors":0.5,"real_word_error_likelihood":0.95,"size":1}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPhraseSuggesterSourceWithContextQuery(t *testing.T) {
- geomapQ := NewSuggesterGeoMapping("location").
- Precision("1km", "5m").
- Neighbors(true).
- FieldName("pin").
- DefaultLocations(GeoPointFromLatLon(0.0, 0.0))
-
- s := NewPhraseSuggester("name").
- Text("Xor the Got-Jewel").
- Analyzer("body").
- Field("bigram").
- Size(1).
- RealWordErrorLikelihood(0.95).
- MaxErrors(0.5).
- GramSize(2).
- Highlight("<em>", "</em>").
- ContextQuery(geomapQ)
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"name":{"text":"Xor the Got-Jewel","phrase":{"analyzer":"body","contexts":{"location":{"default":{"lat":0,"lon":0},"neighbors":true,"path":"pin","precision":["1km","5m"],"type":"geo"}},"field":"bigram","gram_size":2,"highlight":{"post_tag":"\u003c/em\u003e","pre_tag":"\u003cem\u003e"},"max_errors":0.5,"real_word_error_likelihood":0.95,"size":1}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPhraseSuggesterComplexSource(t *testing.T) {
- g1 := NewDirectCandidateGenerator("body").
- SuggestMode("always").
- MinWordLength(1)
-
- g2 := NewDirectCandidateGenerator("reverse").
- SuggestMode("always").
- MinWordLength(1).
- PreFilter("reverse").
- PostFilter("reverse")
-
- s := NewPhraseSuggester("simple_phrase").
- Text("Xor the Got-Jewel").
- Analyzer("body").
- Field("bigram").
- Size(4).
- RealWordErrorLikelihood(0.95).
- Confidence(2.0).
- GramSize(2).
- CandidateGenerators(g1, g2).
- CollateQuery(`"match":{"{{field_name}}" : "{{suggestion}}"}`).
- CollateParams(map[string]interface{}{"field_name": "title"}).
- CollatePreference("_primary").
- CollatePrune(true)
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"simple_phrase":{"text":"Xor the Got-Jewel","phrase":{"analyzer":"body","collate":{"params":{"field_name":"title"},"preference":"_primary","prune":true,"query":"\"match\":{\"{{field_name}}\" : \"{{suggestion}}\"}"},"confidence":2,"direct_generator":[{"field":"body","min_word_length":1,"suggest_mode":"always"},{"field":"reverse","min_word_length":1,"post_filter":"reverse","pre_filter":"reverse","suggest_mode":"always"}],"field":"bigram","gram_size":2,"real_word_error_likelihood":0.95,"size":4}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestPhraseStupidBackoffSmoothingModel(t *testing.T) {
- s := NewStupidBackoffSmoothingModel(0.42)
- src, err := s.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- // The source does NOT include the smoothing model type!
- expected := `{"discount":0.42}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
- if s.Type() != "stupid_backoff" {
- t.Errorf("expected %q, got: %q", "stupid_backoff", s.Type())
- }
-}
-
-func TestPhraseLaplaceSmoothingModel(t *testing.T) {
- s := NewLaplaceSmoothingModel(0.63)
- src, err := s.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- // The source does NOT include the smoothing model type!
- expected := `{"alpha":0.63}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
- if s.Type() != "laplace" {
- t.Errorf("expected %q, got: %q", "laplace", s.Type())
- }
-}
-
-func TestLinearInterpolationSmoothingModel(t *testing.T) {
- s := NewLinearInterpolationSmoothingModel(0.3, 0.2, 0.05)
- src, err := s.Source()
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- // The source does NOT include the smoothing model type!
- expected := `{"bigram_lambda":0.2,"trigram_lambda":0.3,"unigram_lambda":0.05}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
- if s.Type() != "linear_interpolation" {
- t.Errorf("expected %q, got: %q", "linear_interpolation", s.Type())
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_term.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_term.go
index 69e1531f6..9c199f69d 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_term.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/suggester_term.go
@@ -6,7 +6,7 @@ package elastic
// TermSuggester suggests terms based on edit distance.
// For more details, see
-// https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-term.html.
+// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-term.html.
type TermSuggester struct {
Suggester
name string
@@ -178,7 +178,7 @@ func (q *TermSuggester) Source(includeName bool) (interface{}, error) {
if err != nil {
return nil, err
}
- suggester["contexts"] = src
+ suggester["context"] = src
default:
ctxq := make([]interface{}, len(q.contextQueries))
for i, query := range q.contextQueries {
@@ -188,7 +188,7 @@ func (q *TermSuggester) Source(includeName bool) (interface{}, error) {
}
ctxq[i] = src
}
- suggester["contexts"] = ctxq
+ suggester["context"] = ctxq
}
// Specific to term suggester
diff --git a/vendor/gopkg.in/olivere/elastic.v5/suggester_term_test.go b/vendor/gopkg.in/olivere/elastic.v5/suggester_term_test.go
deleted file mode 100644
index d3250f69a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/suggester_term_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTermSuggesterSource(t *testing.T) {
- s := NewTermSuggester("name").
- Text("n").
- Field("suggest")
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"name":{"text":"n","term":{"field":"suggest"}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
-
-func TestTermSuggesterWithPrefixLengthSource(t *testing.T) {
- s := NewTermSuggester("name").
- Text("n").
- Field("suggest").
- PrefixLength(0)
- src, err := s.Source(true)
- if err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(src)
- if err != nil {
- t.Fatalf("marshaling to JSON failed: %v", err)
- }
- got := string(data)
- expected := `{"name":{"text":"n","term":{"field":"suggest","prefix_length":0}}}`
- if got != expected {
- t.Errorf("expected\n%s\n,got:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel.go
index 84f8aec35..2c74fd87e 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel.go
@@ -10,7 +10,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// TasksCancelService can cancel long-running tasks.
@@ -95,7 +95,7 @@ func (s *TasksCancelService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.actions) > 0 {
params.Set("actions", strings.Join(s.actions, ","))
@@ -131,11 +131,7 @@ func (s *TasksCancelService) Do(ctx context.Context) (*TasksListResponse, error)
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel_test.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel_test.go
deleted file mode 100644
index c9d863394..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_cancel_test.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import "testing"
-
-func TestTasksCancelBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- // Cancel all
- got, _, err := client.TasksCancel().buildURL()
- if err != nil {
- t.Fatal(err)
- }
- want := "/_tasks/_cancel"
- if got != want {
- t.Errorf("want %q; got %q", want, got)
- }
-
- // Cancel specific task
- got, _, err = client.TasksCancel().TaskId(42).buildURL()
- if err != nil {
- t.Fatal(err)
- }
- want = "/_tasks/42/_cancel"
- if got != want {
- t.Errorf("want %q; got %q", want, got)
- }
-}
-
-/*
-func TestTasksCancel(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Tasks Management API yet", esversion)
- }
- res, err := client.TasksCancel("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("response is nil")
- }
-}
-*/
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task.go
index 5f63726e4..5368169ec 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task.go
@@ -5,7 +5,7 @@ import (
"fmt"
"net/url"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// TasksGetTaskService retrieves the state of a task in the cluster. It is part of the Task Management API
@@ -85,11 +85,7 @@ func (s *TasksGetTaskService) Do(ctx context.Context) (*TasksGetTaskResponse, er
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task_test.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task_test.go
deleted file mode 100644
index a4da49c74..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_get_task_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "testing"
-)
-
-func TestTasksGetTaskBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- // Get specific task
- got, _, err := client.TasksGetTask().TaskId("123").buildURL()
- if err != nil {
- t.Fatal(err)
- }
- want := "/_tasks/123"
- if got != want {
- t.Errorf("want %q; got %q", want, got)
- }
-}
-
-/*
-func TestTasksGetTask(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t)
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Tasks Management API yet", esversion)
- }
- res, err := client.TasksGetTask().TaskId("123").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("response is nil")
- }
-}
-*/
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_list.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_list.go
index 54299d961..6cad558af 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_list.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/tasks_list.go
@@ -10,12 +10,12 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// TasksListService retrieves the list of currently executing tasks
// on one ore more nodes in the cluster. It is part of the Task Management API
-// documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.0/tasks.html.
+// documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.6/tasks.html.
//
// It is supported as of Elasticsearch 2.3.0.
type TasksListService struct {
@@ -115,7 +115,7 @@ func (s *TasksListService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.actions) > 0 {
params.Set("actions", strings.Join(s.actions, ","))
@@ -160,11 +160,7 @@ func (s *TasksListService) Do(ctx context.Context) (*TasksListResponse, error) {
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, nil)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/tasks_list_test.go b/vendor/gopkg.in/olivere/elastic.v5/tasks_list_test.go
deleted file mode 100644
index 9ecabcd68..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/tasks_list_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
-)
-
-func TestTasksListBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- TaskId []string
- Expected string
- }{
- {
- []string{},
- "/_tasks",
- },
- {
- []string{"42"},
- "/_tasks/42",
- },
- {
- []string{"42", "37"},
- "/_tasks/42%2C37",
- },
- }
-
- for i, test := range tests {
- path, _, err := client.TasksList().TaskId(test.TaskId...).buildURL()
- if err != nil {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
-}
-
-func TestTasksList(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support Tasks Management API yet", esversion)
- }
-
- res, err := client.TasksList().Pretty(true).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("response is nil")
- }
- if len(res.Nodes) == 0 {
- t.Fatalf("expected at least 1 node; got: %d", len(res.Nodes))
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/termvectors.go b/vendor/gopkg.in/olivere/elastic.v5/termvectors.go
index 5943ad14f..6bbcf8f3b 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/termvectors.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/termvectors.go
@@ -10,14 +10,14 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// TermvectorsService returns information and statistics on terms in the
// fields of a particular document. The document could be stored in the
// index or artificially provided by the user.
//
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-termvectors.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-termvectors.html
// for documentation.
type TermvectorsService struct {
client *Client
@@ -169,7 +169,7 @@ func (s *TermvectorsService) Version(version interface{}) *TermvectorsService {
return s
}
-// VersionType specifies a version type ("internal", "external", or "external_gte").
+// VersionType specifies a version type ("internal", "external", "external_gte", or "force").
func (s *TermvectorsService) VersionType(versionType string) *TermvectorsService {
s.versionType = versionType
return s
@@ -217,7 +217,7 @@ func (s *TermvectorsService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if s.dfs != nil {
params.Set("dfs", fmt.Sprintf("%v", *s.dfs))
@@ -316,12 +316,7 @@ func (s *TermvectorsService) Do(ctx context.Context) (*TermvectorsResponse, erro
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "GET",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
if err != nil {
return nil, err
}
@@ -338,7 +333,7 @@ func (s *TermvectorsService) Do(ctx context.Context) (*TermvectorsResponse, erro
// TermvectorsFilterSettings adds additional filters to a Termsvector request.
// It allows to filter terms based on their tf-idf scores.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-termvectors.html#_terms_filtering
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-termvectors.html#_terms_filtering
// for more information.
type TermvectorsFilterSettings struct {
maxNumTerms *int64
diff --git a/vendor/gopkg.in/olivere/elastic.v5/termvectors_test.go b/vendor/gopkg.in/olivere/elastic.v5/termvectors_test.go
deleted file mode 100644
index 0391f2b0a..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/termvectors_test.go
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "testing"
- "time"
-)
-
-func TestTermVectorsBuildURL(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tests := []struct {
- Index string
- Type string
- Id string
- Expected string
- }{
- {
- "twitter",
- "doc",
- "",
- "/twitter/doc/_termvectors",
- },
- {
- "twitter",
- "doc",
- "1",
- "/twitter/doc/1/_termvectors",
- },
- }
-
- for _, test := range tests {
- builder := client.TermVectors(test.Index, test.Type)
- if test.Id != "" {
- builder = builder.Id(test.Id)
- }
- path, _, err := builder.buildURL()
- if err != nil {
- t.Fatal(err)
- }
- if path != test.Expected {
- t.Errorf("expected %q; got: %q", test.Expected, path)
- }
- }
-}
-
-func TestTermVectorsWithId(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
-
- // Add a document
- indexResult, err := client.Index().
- Index(testIndexName).
- Type("doc").
- Id("1").
- BodyJson(&tweet1).
- Refresh("true").
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if indexResult == nil {
- t.Errorf("expected result to be != nil; got: %v", indexResult)
- }
-
- // TermVectors by specifying ID
- field := "Message"
- result, err := client.TermVectors(testIndexName, "doc").
- Id("1").
- Fields(field).
- FieldStatistics(true).
- TermStatistics(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if result == nil {
- t.Fatal("expected to return information and statistics")
- }
- if !result.Found {
- t.Errorf("expected found to be %v; got: %v", true, result.Found)
- }
-}
-
-func TestTermVectorsWithDoc(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Travis lags sometimes
- if isTravis() {
- time.Sleep(2 * time.Second)
- }
-
- // TermVectors by specifying Doc
- var doc = map[string]interface{}{
- "fullname": "John Doe",
- "text": "twitter test test test",
- }
- var perFieldAnalyzer = map[string]string{
- "fullname": "keyword",
- }
-
- result, err := client.TermVectors(testIndexName, "doc").
- Doc(doc).
- PerFieldAnalyzer(perFieldAnalyzer).
- FieldStatistics(true).
- TermStatistics(true).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if result == nil {
- t.Fatal("expected to return information and statistics")
- }
- if !result.Found {
- t.Errorf("expected found to be %v; got: %v", true, result.Found)
- }
-}
-
-func TestTermVectorsWithFilter(t *testing.T) {
- client := setupTestClientAndCreateIndex(t)
-
- // Travis lags sometimes
- if isTravis() {
- time.Sleep(2 * time.Second)
- }
-
- // TermVectors by specifying Doc
- var doc = map[string]interface{}{
- "fullname": "John Doe",
- "text": "twitter test test test",
- }
- var perFieldAnalyzer = map[string]string{
- "fullname": "keyword",
- }
-
- result, err := client.TermVectors(testIndexName, "doc").
- Doc(doc).
- PerFieldAnalyzer(perFieldAnalyzer).
- FieldStatistics(true).
- TermStatistics(true).
- Filter(NewTermvectorsFilterSettings().MinTermFreq(1)).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if result == nil {
- t.Fatal("expected to return information and statistics")
- }
- if !result.Found {
- t.Errorf("expected found to be %v; got: %v", true, result.Found)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/update.go b/vendor/gopkg.in/olivere/elastic.v5/update.go
index 5507fae4c..1718bc585 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/update.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/update.go
@@ -10,11 +10,11 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// UpdateService updates a document in Elasticsearch.
-// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/docs-update.html
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html
// for details.
type UpdateService struct {
client *Client
@@ -105,7 +105,7 @@ func (b *UpdateService) Version(version int64) *UpdateService {
return b
}
-// VersionType is e.g. "internal".
+// VersionType is one of "internal" or "force".
func (b *UpdateService) VersionType(versionType string) *UpdateService {
b.versionType = versionType
return b
@@ -293,12 +293,7 @@ func (b *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) {
}
// Get response
- res, err := b.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := b.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
@@ -313,15 +308,12 @@ func (b *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) {
// UpdateResponse is the result of updating a document in Elasticsearch.
type UpdateResponse struct {
- Index string `json:"_index,omitempty"`
- Type string `json:"_type,omitempty"`
- Id string `json:"_id,omitempty"`
- Version int64 `json:"_version,omitempty"`
+ Index string `json:"_index"`
+ Type string `json:"_type"`
+ Id string `json:"_id"`
+ Version int `json:"_version"`
+ Shards *shardsInfo `json:"_shards"`
Result string `json:"result,omitempty"`
- Shards *shardsInfo `json:"_shards,omitempty"`
- SeqNo int64 `json:"_seq_no,omitempty"`
- PrimaryTerm int64 `json:"_primary_term,omitempty"`
- Status int `json:"status,omitempty"`
ForcedRefresh bool `json:"forced_refresh,omitempty"`
GetResult *GetResult `json:"get,omitempty"`
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/update_by_query.go b/vendor/gopkg.in/olivere/elastic.v5/update_by_query.go
index 953d67388..505e1e834 100644
--- a/vendor/gopkg.in/olivere/elastic.v5/update_by_query.go
+++ b/vendor/gopkg.in/olivere/elastic.v5/update_by_query.go
@@ -10,7 +10,7 @@ import (
"net/url"
"strings"
- "github.com/olivere/elastic/uritemplates"
+ "gopkg.in/olivere/elastic.v5/uritemplates"
)
// UpdateByQueryService is documented at https://www.elastic.co/guide/en/elasticsearch/plugins/master/plugins-reindex.html.
@@ -447,7 +447,7 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) {
// Add query string parameters
params := url.Values{}
if s.pretty {
- params.Set("pretty", "true")
+ params.Set("pretty", "1")
}
if len(s.xSource) > 0 {
params.Set("_source", strings.Join(s.xSource, ","))
@@ -636,12 +636,7 @@ func (s *UpdateByQueryService) Do(ctx context.Context) (*BulkIndexByScrollRespon
}
// Get HTTP response
- res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
- Method: "POST",
- Path: path,
- Params: params,
- Body: body,
- })
+ res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
if err != nil {
return nil, err
}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/update_by_query_test.go b/vendor/gopkg.in/olivere/elastic.v5/update_by_query_test.go
deleted file mode 100644
index fde924dd5..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/update_by_query_test.go
+++ /dev/null
@@ -1,147 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestUpdateByQueryBuildURL(t *testing.T) {
- client := setupTestClient(t)
-
- tests := []struct {
- Indices []string
- Types []string
- Expected string
- ExpectErr bool
- }{
- {
- []string{},
- []string{},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{},
- "/index1/_update_by_query",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{},
- "/index1%2Cindex2/_update_by_query",
- false,
- },
- {
- []string{},
- []string{"type1"},
- "",
- true,
- },
- {
- []string{"index1"},
- []string{"type1"},
- "/index1/type1/_update_by_query",
- false,
- },
- {
- []string{"index1", "index2"},
- []string{"type1", "type2"},
- "/index1%2Cindex2/type1%2Ctype2/_update_by_query",
- false,
- },
- }
-
- for i, test := range tests {
- builder := client.UpdateByQuery().Index(test.Indices...).Type(test.Types...)
- err := builder.Validate()
- if err != nil {
- if !test.ExpectErr {
- t.Errorf("case #%d: %v", i+1, err)
- continue
- }
- } else {
- // err == nil
- if test.ExpectErr {
- t.Errorf("case #%d: expected error", i+1)
- continue
- }
- path, _, _ := builder.buildURL()
- if path != test.Expected {
- t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
- }
- }
- }
-}
-
-func TestUpdateByQueryBodyWithQuery(t *testing.T) {
- client := setupTestClient(t)
- out, err := client.UpdateByQuery().Query(NewTermQuery("user", "olivere")).getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"query":{"term":{"user":"olivere"}}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestUpdateByQueryBodyWithQueryAndScript(t *testing.T) {
- client := setupTestClient(t)
- out, err := client.UpdateByQuery().
- Query(NewTermQuery("user", "olivere")).
- Script(NewScriptInline("ctx._source.likes++")).
- getBody()
- if err != nil {
- t.Fatal(err)
- }
- b, err := json.Marshal(out)
- if err != nil {
- t.Fatal(err)
- }
- got := string(b)
- want := `{"query":{"term":{"user":"olivere"}},"script":{"source":"ctx._source.likes++"}}`
- if got != want {
- t.Fatalf("\ngot %s\nwant %s", got, want)
- }
-}
-
-func TestUpdateByQuery(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) //, SetTraceLog(log.New(os.Stdout, "", 0)))
- esversion, err := client.ElasticsearchVersion(DefaultURL)
- if err != nil {
- t.Fatal(err)
- }
- if esversion < "2.3.0" {
- t.Skipf("Elasticsearch %v does not support update-by-query yet", esversion)
- }
-
- sourceCount, err := client.Count(testIndexName).Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if sourceCount <= 0 {
- t.Fatalf("expected more than %d documents; got: %d", 0, sourceCount)
- }
-
- res, err := client.UpdateByQuery(testIndexName).ProceedOnVersionConflict().Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("response is nil")
- }
- if res.Updated != sourceCount {
- t.Fatalf("expected %d; got: %d", sourceCount, res.Updated)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/update_integration_test.go b/vendor/gopkg.in/olivere/elastic.v5/update_integration_test.go
deleted file mode 100644
index f36925298..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/update_integration_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "testing"
-)
-
-func TestUpdateWithScript(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- // Get original
- getRes, err := client.Get().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- var original tweet
- if err := json.Unmarshal(*getRes.Source, &original); err != nil {
- t.Fatal(err)
- }
-
- // Update with script
- updRes, err := client.Update().Index(testIndexName).Type("doc").Id("1").
- Script(
- NewScript(`ctx._source.message = "Updated message text."`).Lang("painless"),
- ).
- Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- if updRes == nil {
- t.Fatal("response is nil")
- }
- if want, have := "updated", updRes.Result; want != have {
- t.Fatalf("want Result = %q, have %v", want, have)
- }
-
- // Get new version
- getRes, err = client.Get().Index(testIndexName).Type("doc").Id("1").Do(context.TODO())
- if err != nil {
- t.Fatal(err)
- }
- var updated tweet
- if err := json.Unmarshal(*getRes.Source, &updated); err != nil {
- t.Fatal(err)
- }
-
- if want, have := original.User, updated.User; want != have {
- t.Fatalf("want User = %q, have %v", want, have)
- }
- if want, have := "Updated message text.", updated.Message; want != have {
- t.Fatalf("want Message = %q, have %v", want, have)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/update_test.go b/vendor/gopkg.in/olivere/elastic.v5/update_test.go
deleted file mode 100644
index 1f04cedd6..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/update_test.go
+++ /dev/null
@@ -1,262 +0,0 @@
-// Copyright 2012-present Oliver Eilhard. All rights reserved.
-// Use of this source code is governed by a MIT-license.
-// See http://olivere.mit-license.org/license.txt for details.
-
-package elastic
-
-import (
- "context"
- "encoding/json"
- "net/url"
- "testing"
-)
-
-func TestUpdateViaScript(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- update := client.Update().
- Index("test").Type("type1").Id("1").
- Script(NewScript("ctx._source.tags += tag").Params(map[string]interface{}{"tag": "blue"}).Lang("groovy"))
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/test/type1/1/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{}
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"script":{"lang":"groovy","params":{"tag":"blue"},"source":"ctx._source.tags += tag"}}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateViaScriptId(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- scriptParams := map[string]interface{}{
- "pageViewEvent": map[string]interface{}{
- "url": "foo.com/bar",
- "response": 404,
- "time": "2014-01-01 12:32",
- },
- }
- script := NewScriptStored("my_web_session_summariser").Params(scriptParams)
-
- update := client.Update().
- Index("sessions").Type("session").Id("dh3sgudg8gsrgl").
- Script(script).
- ScriptedUpsert(true).
- Upsert(map[string]interface{}{})
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/sessions/session/dh3sgudg8gsrgl/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{}
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"script":{"id":"my_web_session_summariser","params":{"pageViewEvent":{"response":404,"time":"2014-01-01 12:32","url":"foo.com/bar"}}},"scripted_upsert":true,"upsert":{}}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateViaScriptAndUpsert(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- update := client.Update().
- Index("test").Type("type1").Id("1").
- Script(NewScript("ctx._source.counter += count").Params(map[string]interface{}{"count": 4})).
- Upsert(map[string]interface{}{"counter": 1})
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/test/type1/1/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{}
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"script":{"params":{"count":4},"source":"ctx._source.counter += count"},"upsert":{"counter":1}}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateViaDoc(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- update := client.Update().
- Index("test").Type("type1").Id("1").
- Doc(map[string]interface{}{"name": "new_name"}).
- DetectNoop(true)
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/test/type1/1/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{}
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"detect_noop":true,"doc":{"name":"new_name"}}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateViaDocAndUpsert(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- update := client.Update().
- Index("test").Type("type1").Id("1").
- Doc(map[string]interface{}{"name": "new_name"}).
- DocAsUpsert(true).
- Timeout("1s").
- Refresh("true")
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/test/type1/1/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{"refresh": []string{"true"}, "timeout": []string{"1s"}}
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"doc":{"name":"new_name"},"doc_as_upsert":true}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateViaDocAndUpsertAndFetchSource(t *testing.T) {
- client := setupTestClient(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- update := client.Update().
- Index("test").Type("type1").Id("1").
- Doc(map[string]interface{}{"name": "new_name"}).
- DocAsUpsert(true).
- Timeout("1s").
- Refresh("true").
- FetchSource(true)
- path, params, err := update.url()
- if err != nil {
- t.Fatalf("expected to return URL, got: %v", err)
- }
- expectedPath := `/test/type1/1/_update`
- if expectedPath != path {
- t.Errorf("expected URL path\n%s\ngot:\n%s", expectedPath, path)
- }
- expectedParams := url.Values{
- "refresh": []string{"true"},
- "timeout": []string{"1s"},
- }
- if expectedParams.Encode() != params.Encode() {
- t.Errorf("expected URL parameters\n%s\ngot:\n%s", expectedParams.Encode(), params.Encode())
- }
- body, err := update.body()
- if err != nil {
- t.Fatalf("expected to return body, got: %v", err)
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"_source":true,"doc":{"name":"new_name"},"doc_as_upsert":true}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
-
-func TestUpdateAndFetchSource(t *testing.T) {
- client := setupTestClientAndCreateIndexAndAddDocs(t) // , SetTraceLog(log.New(os.Stdout, "", 0)))
-
- res, err := client.Update().
- Index(testIndexName).Type("doc").Id("1").
- Doc(map[string]interface{}{"user": "sandrae"}).
- DetectNoop(true).
- FetchSource(true).
- Do(context.Background())
- if err != nil {
- t.Fatal(err)
- }
- if res == nil {
- t.Fatal("expected response != nil")
- }
- if res.GetResult == nil {
- t.Fatal("expected GetResult != nil")
- }
- data, err := json.Marshal(res.GetResult.Source)
- if err != nil {
- t.Fatalf("expected to marshal body as JSON, got: %v", err)
- }
- got := string(data)
- expected := `{"user":"sandrae","message":"Welcome to Golang and Elasticsearch.","retweets":0,"created":"0001-01-01T00:00:00Z"}`
- if got != expected {
- t.Errorf("expected\n%s\ngot:\n%s", expected, got)
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/uritemplates/utils_test.go b/vendor/gopkg.in/olivere/elastic.v5/uritemplates/utils_test.go
deleted file mode 100644
index 633949b6f..000000000
--- a/vendor/gopkg.in/olivere/elastic.v5/uritemplates/utils_test.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package uritemplates
-
-import (
- "testing"
-)
-
-type ExpandTest struct {
- in string
- expansions map[string]string
- want string
-}
-
-var expandTests = []ExpandTest{
- // #0: no expansions
- {
- "http://www.golang.org/",
- map[string]string{},
- "http://www.golang.org/",
- },
- // #1: one expansion, no escaping
- {
- "http://www.golang.org/{bucket}/delete",
- map[string]string{
- "bucket": "red",
- },
- "http://www.golang.org/red/delete",
- },
- // #2: one expansion, with hex escapes
- {
- "http://www.golang.org/{bucket}/delete",
- map[string]string{
- "bucket": "red/blue",
- },
- "http://www.golang.org/red%2Fblue/delete",
- },
- // #3: one expansion, with space
- {
- "http://www.golang.org/{bucket}/delete",
- map[string]string{
- "bucket": "red or blue",
- },
- "http://www.golang.org/red%20or%20blue/delete",
- },
- // #4: expansion not found
- {
- "http://www.golang.org/{object}/delete",
- map[string]string{
- "bucket": "red or blue",
- },
- "http://www.golang.org//delete",
- },
- // #5: multiple expansions
- {
- "http://www.golang.org/{one}/{two}/{three}/get",
- map[string]string{
- "one": "ONE",
- "two": "TWO",
- "three": "THREE",
- },
- "http://www.golang.org/ONE/TWO/THREE/get",
- },
- // #6: utf-8 characters
- {
- "http://www.golang.org/{bucket}/get",
- map[string]string{
- "bucket": "£100",
- },
- "http://www.golang.org/%C2%A3100/get",
- },
- // #7: punctuations
- {
- "http://www.golang.org/{bucket}/get",
- map[string]string{
- "bucket": `/\@:,.*~`,
- },
- "http://www.golang.org/%2F%5C%40%3A%2C.%2A~/get",
- },
- // #8: mis-matched brackets
- {
- "http://www.golang.org/{bucket/get",
- map[string]string{
- "bucket": "red",
- },
- "",
- },
- // #9: "+" prefix for suppressing escape
- // See also: http://tools.ietf.org/html/rfc6570#section-3.2.3
- {
- "http://www.golang.org/{+topic}",
- map[string]string{
- "topic": "/topics/myproject/mytopic",
- },
- // The double slashes here look weird, but it's intentional
- "http://www.golang.org//topics/myproject/mytopic",
- },
-}
-
-func TestExpand(t *testing.T) {
- for i, test := range expandTests {
- got, _ := Expand(test.in, test.expansions)
- if got != test.want {
- t.Errorf("got %q expected %q in test %d", got, test.want, i)
- }
- }
-}
diff --git a/vendor/gopkg.in/olivere/elastic.v5/validate.go b/vendor/gopkg.in/olivere/elastic.v5/validate.go
new file mode 100644
index 000000000..69a43cdd9
--- /dev/null
+++ b/vendor/gopkg.in/olivere/elastic.v5/validate.go
@@ -0,0 +1,280 @@
+// Copyright 2012-present Oliver Eilhard. All rights reserved.
+// Use of this source code is governed by a MIT-license.
+// See http://olivere.mit-license.org/license.txt for details.
+
+package elastic
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "gopkg.in/olivere/elastic.v5/uritemplates"
+)
+
+// ValidateService allows a user to validate a potentially
+// expensive query without executing it.
+// See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-validate.html.
+type ValidateService struct {
+ client *Client
+ pretty bool
+ index []string
+ typ []string
+ q string
+ explain *bool
+ rewrite *bool
+ allShards *bool
+ lenient *bool
+ analyzer string
+ df string
+ analyzeWildcard *bool
+ defaultOperator string
+ ignoreUnavailable *bool
+ allowNoIndices *bool
+ expandWildcards string
+ bodyJson interface{}
+ bodyString string
+}
+
+// NewValidateService creates a new ValidateService.
+func NewValidateService(client *Client) *ValidateService {
+ return &ValidateService{
+ client: client,
+ }
+}
+
+// Index sets the names of the indices to use for search.
+func (s *ValidateService) Index(index ...string) *ValidateService {
+ s.index = append(s.index, index...)
+ return s
+}
+
+// Types adds search restrictions for a list of types.
+func (s *ValidateService) Type(typ ...string) *ValidateService {
+ s.typ = append(s.typ, typ...)
+ return s
+}
+
+// Lenient specifies whether format-based query failures
+// (such as providing text to a numeric field) should be ignored.
+func (s *ValidateService) Lenient(lenient bool) *ValidateService {
+ s.lenient = &lenient
+ return s
+}
+
+// Query in the Lucene query string syntax.
+func (s *ValidateService) Q(q string) *ValidateService {
+ s.q = q
+ return s
+}
+
+// An explain parameter can be specified to get more detailed information about why a query failed.
+func (s *ValidateService) Explain(explain *bool) *ValidateService {
+ s.explain = explain
+ return s
+}
+
+// Provide a more detailed explanation showing the actual Lucene query that will be executed.
+func (s *ValidateService) Rewrite(rewrite *bool) *ValidateService {
+ s.rewrite = rewrite
+ return s
+}
+
+// Execute validation on all shards instead of one random shard per index.
+func (s *ValidateService) AllShards(allShards *bool) *ValidateService {
+ s.allShards = allShards
+ return s
+}
+
+// AnalyzeWildcard specifies whether wildcards and prefix queries
+// in the query string query should be analyzed (default: false).
+func (s *ValidateService) AnalyzeWildcard(analyzeWildcard bool) *ValidateService {
+ s.analyzeWildcard = &analyzeWildcard
+ return s
+}
+
+// Analyzer is the analyzer for the query string query.
+func (s *ValidateService) Analyzer(analyzer string) *ValidateService {
+ s.analyzer = analyzer
+ return s
+}
+
+// Df is the default field for query string query (default: _all).
+func (s *ValidateService) Df(df string) *ValidateService {
+ s.df = df
+ return s
+}
+
+// DefaultOperator is the default operator for query string query (AND or OR).
+func (s *ValidateService) DefaultOperator(defaultOperator string) *ValidateService {
+ s.defaultOperator = defaultOperator
+ return s
+}
+
+// Pretty indicates that the JSON response be indented and human readable.
+func (s *ValidateService) Pretty(pretty bool) *ValidateService {
+ s.pretty = pretty
+ return s
+}
+
+// Query sets a query definition using the Query DSL.
+func (s *ValidateService) Query(query Query) *ValidateService {
+ src, err := query.Source()
+ if err != nil {
+ // Do nothing in case of an error
+ return s
+ }
+ body := make(map[string]interface{})
+ body["query"] = src
+ s.bodyJson = body
+ return s
+}
+
+// IgnoreUnavailable indicates whether the specified concrete indices
+// should be ignored when unavailable (missing or closed).
+func (s *ValidateService) IgnoreUnavailable(ignoreUnavailable bool) *ValidateService {
+ s.ignoreUnavailable = &ignoreUnavailable
+ return s
+}
+
+// AllowNoIndices indicates whether to ignore if a wildcard indices
+// expression resolves into no concrete indices. (This includes `_all` string
+// or when no indices have been specified).
+func (s *ValidateService) AllowNoIndices(allowNoIndices bool) *ValidateService {
+ s.allowNoIndices = &allowNoIndices
+ return s
+}
+
+// ExpandWildcards indicates whether to expand wildcard expression to
+// concrete indices that are open, closed or both.
+func (s *ValidateService) ExpandWildcards(expandWildcards string) *ValidateService {
+ s.expandWildcards = expandWildcards
+ return s
+}
+
+// BodyJson sets the query definition using the Query DSL.
+func (s *ValidateService) BodyJson(body interface{}) *ValidateService {
+ s.bodyJson = body
+ return s
+}
+
+// BodyString sets the query definition using the Query DSL as a string.
+func (s *ValidateService) BodyString(body string) *ValidateService {
+ s.bodyString = body
+ return s
+}
+
+// buildURL builds the URL for the operation.
+func (s *ValidateService) buildURL() (string, url.Values, error) {
+ var err error
+ var path string
+ // Build URL
+ if len(s.index) > 0 && len(s.typ) > 0 {
+ path, err = uritemplates.Expand("/{index}/{type}/_validate/query", map[string]string{
+ "index": strings.Join(s.index, ","),
+ "type": strings.Join(s.typ, ","),
+ })
+ } else if len(s.index) > 0 {
+ path, err = uritemplates.Expand("/{index}/_validate/query", map[string]string{
+ "index": strings.Join(s.index, ","),
+ })
+ } else {
+ path, err = uritemplates.Expand("/_validate/query", map[string]string{
+ "type": strings.Join(s.typ, ","),
+ })
+ }
+ if err != nil {
+ return "", url.Values{}, err
+ }
+
+ // Add query string parameters
+ params := url.Values{}
+ if s.pretty {
+ params.Set("pretty", "true")
+ }
+ if s.explain != nil {
+ params.Set("explain", fmt.Sprintf("%v", *s.explain))
+ }
+ if s.rewrite != nil {
+ params.Set("rewrite", fmt.Sprintf("%v", *s.rewrite))
+ }
+ if s.allShards != nil {
+ params.Set("all_shards", fmt.Sprintf("%v", *s.allShards))
+ }
+ if s.defaultOperator != "" {
+ params.Set("default_operator", s.defaultOperator)
+ }
+ if s.lenient != nil {
+ params.Set("lenient", fmt.Sprintf("%v", *s.lenient))
+ }
+ if s.q != "" {
+ params.Set("q", s.q)
+ }
+ if s.analyzeWildcard != nil {
+ params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard))
+ }
+ if s.analyzer != "" {
+ params.Set("analyzer", s.analyzer)
+ }
+ if s.df != "" {
+ params.Set("df", s.df)
+ }
+ if s.allowNoIndices != nil {
+ params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
+ }
+ if s.expandWildcards != "" {
+ params.Set("expand_wildcards", s.expandWildcards)
+ }
+ if s.ignoreUnavailable != nil {
+ params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
+ }
+ return path, params, nil
+}
+
+// Validate checks if the operation is valid.
+func (s *ValidateService) Validate() error {
+ return nil
+}
+
+// Do executes the operation.
+func (s *ValidateService) Do(ctx context.Context) (*ValidateResponse, error) {
+ // Check pre-conditions
+ if err := s.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Get URL for request
+ path, params, err := s.buildURL()
+ if err != nil {
+ return nil, err
+ }
+
+ // Setup HTTP request body
+ var body interface{}
+ if s.bodyJson != nil {
+ body = s.bodyJson
+ } else {
+ body = s.bodyString
+ }
+
+ // Get HTTP response
+ res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return operation response
+ ret := new(ValidateResponse)
+ if err := s.client.decoder.Decode(res.Body, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+// ValidateResponse is the response of ValidateService.Do.
+type ValidateResponse struct {
+ Valid bool `json:"valid"`
+ Shards map[string]interface{} `json:"_shards"`
+ Explanations []interface{} `json:"explanations"`
+}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/.travis.yml b/vendor/gopkg.in/throttled/throttled.v2/.travis.yml
index 0c19e2cd5..29225d7af 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/.travis.yml
+++ b/vendor/gopkg.in/throttled/throttled.v2/.travis.yml
@@ -3,13 +3,8 @@ sudo: false
language: go
go:
- - 1.7
- - 1.8
- - 1.9
- # 1.x builds the latest in that series. Also try to add other versions here
- # as they come up so that we're pretty sure that we're maintaining
- # backwards compatibility.
- - 1.x
+ - 1.3
+ - tip
notifications:
email: false
@@ -17,6 +12,13 @@ notifications:
services:
- redis-server
-install: make get-deps
+install:
+ - make get-deps
+ # Move to the gopkg location that rather than the default clone location
+ # otherwise Go 1.4+ complains about incorrect import paths.
+ - export GOPKG_DIR=$GOPATH/src/gopkg.in/throttled
+ - mkdir -p $GOPKG_DIR
+ - mv $TRAVIS_BUILD_DIR $GOPKG_DIR/throttled.v2
+ - cd $GOPKG_DIR/throttled.v2
script: make
diff --git a/vendor/gopkg.in/throttled/throttled.v2/Makefile b/vendor/gopkg.in/throttled/throttled.v2/Makefile
index d6e33c516..cfc235c31 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/Makefile
+++ b/vendor/gopkg.in/throttled/throttled.v2/Makefile
@@ -11,7 +11,9 @@ bench:
lint:
gofmt -l .
+ifneq ($(TRAVIS_GO_VERSION),1.3) # go vet doesn't play nicely on 1.3
go vet ./...
+endif
which golint # Fail if golint doesn't exist
-golint . # Don't fail on golint warnings themselves
-golint store # Don't fail on golint warnings themselves
diff --git a/vendor/gopkg.in/throttled/throttled.v2/README.md b/vendor/gopkg.in/throttled/throttled.v2/README.md
index d0e0609a5..b18dcbcc6 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/README.md
+++ b/vendor/gopkg.in/throttled/throttled.v2/README.md
@@ -1,7 +1,7 @@
-# Throttled [![build status](https://secure.travis-ci.org/throttled/throttled.svg)](https://travis-ci.org/throttled/throttled) [![GoDoc](https://godoc.org/github.com/throttled/throttled?status.svg)](https://godoc.org/github.com/throttled/throttled)
+# Throttled [![build status](https://secure.travis-ci.org/throttled/throttled.png)](https://travis-ci.org/throttled/throttled) [![GoDoc](https://godoc.org/gopkg.in/throttled/throttled.v2?status.png)](https://godoc.org/gopkg.in/throttled/throttled.v2)
-Package throttled implements rate limiting using the [generic cell rate
-algorithm][gcra] to limit access to resources such as HTTP endpoints.
+Package throttled implements rate limiting access to resources such as
+HTTP endpoints.
The 2.0.0 release made some major changes to the throttled API. If
this change broke your code in problematic ways or you wish a feature
@@ -11,9 +11,16 @@ what our users need. Thanks!
## Installation
-```sh
-go get -u github.com/throttled/throttled`
-```
+throttled uses gopkg.in for semantic versioning:
+`go get gopkg.in/throttled/throttled.v2`
+
+As of July 27, 2015, the package is located under its own Github
+organization. Please adjust your imports to
+`gopkg.in/throttled/throttled.v2`.
+
+The 1.x release series is compatible with the original, unversioned
+library written by [Martin Angers][puerkitobio]. There is a
+[blog post explaining that version's usage on 0value.com][blog].
## Documentation
@@ -22,39 +29,57 @@ example demonstrates the usage of HTTPLimiter for rate-limiting access
to an http.Handler to 20 requests per path per minute with bursts of
up to 5 additional requests:
-```go
-store, err := memstore.New(65536)
-if err != nil {
- log.Fatal(err)
-}
+ store, err := memstore.New(65536)
+ if err != nil {
+ log.Fatal(err)
+ }
-quota := throttled.RateQuota{throttled.PerMin(20), 5}
-rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
-if err != nil {
- log.Fatal(err)
-}
+ quota := throttled.RateQuota{throttled.PerMin(20), 5}
+ rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
+ if err != nil {
+ log.Fatal(err)
+ }
-httpRateLimiter := throttled.HTTPRateLimiter{
- RateLimiter: rateLimiter,
- VaryBy: &throttled.VaryBy{Path: true},
-}
+ httpRateLimiter := throttled.HTTPRateLimiter{
+ RateLimiter: rateLimiter,
+ VaryBy: &throttled.VaryBy{Path: true},
+ }
-http.ListenAndServe(":8080", httpRateLimiter.RateLimit(myHandler))
-```
+ http.ListenAndServe(":8080", httpRateLimiter.RateLimit(myHandler))
+
+## Contributing
-## Related Projects
+Since throttled uses gopkg.in for versioning, running `go get` against
+a fork or cloning from Github to the default path will break
+imports. Instead, use the following process for setting up your
+environment and contributing:
+
+```sh
+# Retrieve the source and dependencies.
+go get gopkg.in/throttled/throttled.v2/...
+
+# Fork the project on Github. For all following directions replace
+# <username> with your Github username. Add your fork as a remote.
+cd $GOPATH/src/gopkg.in/throttled/throttled.v2
+git remote add fork git@github.com:<username>/throttled.git
+
+# Create a branch, make your changes, test them and commit.
+git checkout -b my-new-feature
+# <do some work>
+make test
+git commit -a
+git push -u fork my-new-feature
+```
-See [throttled/gcra][throttled-gcra] for a list of other projects related to
-rate limiting and GCRA.
+When your changes are ready, [open a pull request][pr] using "compare
+across forks".
## License
-The [BSD 3-clause license][bsd]. Copyright (c) 2014 Martin Angers and contributors.
+The [BSD 3-clause license][bsd]. Copyright (c) 2014 Martin Angers and Contributors.
[blog]: http://0value.com/throttled--guardian-of-the-web-server
[bsd]: https://opensource.org/licenses/BSD-3-Clause
-[doc]: https://godoc.org/github.com/throttled/throttled
-[gcra]: https://en.wikipedia.org/wiki/Generic_cell_rate_algorithm
+[doc]: https://godoc.org/gopkg.in/throttled/throttled.v2
[puerkitobio]: https://github.com/puerkitobio/
[pr]: https://github.com/throttled/throttled/compare
-[throttled-gcra]: https://github.com/throttled/gcra
diff --git a/vendor/gopkg.in/throttled/throttled.v2/deprecated_test.go b/vendor/gopkg.in/throttled/throttled.v2/deprecated_test.go
deleted file mode 100644
index e0453d78f..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/deprecated_test.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package throttled_test
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/throttled/throttled"
- "github.com/throttled/throttled/store"
-)
-
-// Ensure that the current implementation remains compatible with the
-// supported but deprecated usage until the next major version.
-func TestDeprecatedUsage(t *testing.T) {
- // Declare interfaces to statically check that names haven't changed
- var st throttled.Store
- var thr *throttled.Throttler
- var q throttled.Quota
-
- st = store.NewMemStore(100)
- vary := &throttled.VaryBy{Path: true}
- q = throttled.PerMin(2)
- thr = throttled.RateLimit(q, vary, st)
- handler := thr.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- }))
-
- cases := []struct {
- path string
- code int
- headers map[string]string
- }{
- {"/foo", 200, map[string]string{"X-Ratelimit-Limit": "2", "X-Ratelimit-Remaining": "1", "X-Ratelimit-Reset": "30"}},
- {"/foo", 200, map[string]string{"X-Ratelimit-Limit": "2", "X-Ratelimit-Remaining": "0", "X-Ratelimit-Reset": "60"}},
- {"/foo", 429, map[string]string{"X-Ratelimit-Limit": "2", "X-Ratelimit-Remaining": "0", "X-Ratelimit-Reset": "60", "Retry-After": "30"}},
- {"/bar", 200, map[string]string{"X-Ratelimit-Limit": "2", "X-Ratelimit-Remaining": "1", "X-Ratelimit-Reset": "30"}},
- }
-
- for i, c := range cases {
- req, err := http.NewRequest("GET", c.path, nil)
- if err != nil {
- t.Fatal(err)
- }
-
- rr := httptest.NewRecorder()
- handler.ServeHTTP(rr, req)
- if have, want := rr.Code, c.code; have != want {
- t.Errorf("Expected request %d at %s to return %d but got %d",
- i, c.path, want, have)
- }
-
- for name, want := range c.headers {
- if have := rr.HeaderMap.Get(name); have != want {
- t.Errorf("Expected request %d at %s to have header '%s: %s' but got '%s'",
- i, c.path, name, want, have)
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/doc.go b/vendor/gopkg.in/throttled/throttled.v2/doc.go
index cb14a65a6..302c2bed7 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/doc.go
+++ b/vendor/gopkg.in/throttled/throttled.v2/doc.go
@@ -1,3 +1,3 @@
// Package throttled implements rate limiting access to resources such
// as HTTP endpoints.
-package throttled // import "github.com/throttled/throttled"
+package throttled // import "gopkg.in/throttled/throttled.v2"
diff --git a/vendor/gopkg.in/throttled/throttled.v2/example_test.go b/vendor/gopkg.in/throttled/throttled.v2/example_test.go
deleted file mode 100644
index 7c4c5df14..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/example_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package throttled_test
-
-import (
- "fmt"
- "log"
- "net/http"
-
- "github.com/throttled/throttled"
- "github.com/throttled/throttled/store/memstore"
-)
-
-var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hi there!"))
-})
-
-// ExampleHTTPRateLimiter demonstrates the usage of HTTPRateLimiter
-// for rate-limiting access to an http.Handler to 20 requests per path
-// per minute with a maximum burst of 5 requests.
-func ExampleHTTPRateLimiter() {
- store, err := memstore.New(65536)
- if err != nil {
- log.Fatal(err)
- }
-
- // Maximum burst of 5 which refills at 20 tokens per minute.
- quota := throttled.RateQuota{throttled.PerMin(20), 5}
-
- rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
- if err != nil {
- log.Fatal(err)
- }
-
- httpRateLimiter := throttled.HTTPRateLimiter{
- RateLimiter: rateLimiter,
- VaryBy: &throttled.VaryBy{Path: true},
- }
-
- http.ListenAndServe(":8080", httpRateLimiter.RateLimit(myHandler))
-}
-
-// Demonstrates direct use of GCRARateLimiter's RateLimit function (and the
-// more general RateLimiter interface). This should be used anywhere where
-// granular control over rate limiting is required.
-func ExampleGCRARateLimiter() {
- store, err := memstore.New(65536)
- if err != nil {
- log.Fatal(err)
- }
-
- // Maximum burst of 5 which refills at 1 token per hour.
- quota := throttled.RateQuota{throttled.PerHour(1), 5}
-
- rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
- if err != nil {
- log.Fatal(err)
- }
-
- // Bucket according to the number i / 10 (so 1 falls into the bucket 0
- // while 11 falls into the bucket 1). This has the effect of allowing a
- // burst of 5 plus 1 (a single emission interval) on every ten iterations
- // of the loop. See the output for better clarity here.
- //
- // We also refill the bucket at 1 token per hour, but that has no effect
- // for the purposes of this example.
- for i := 0; i < 20; i++ {
- bucket := fmt.Sprintf("by-order:%v", i/10)
-
- limited, result, err := rateLimiter.RateLimit(bucket, 1)
- if err != nil {
- log.Fatal(err)
- }
-
- if limited {
- fmt.Printf("Iteration %2v; bucket %v: FAILED. Rate limit exceeded.\n",
- i, bucket)
- } else {
- fmt.Printf("Iteration %2v; bucket %v: Operation successful (remaining=%v).\n",
- i, bucket, result.Remaining)
- }
- }
-
- // Output:
- // Iteration 0; bucket by-order:0: Operation successful (remaining=5).
- // Iteration 1; bucket by-order:0: Operation successful (remaining=4).
- // Iteration 2; bucket by-order:0: Operation successful (remaining=3).
- // Iteration 3; bucket by-order:0: Operation successful (remaining=2).
- // Iteration 4; bucket by-order:0: Operation successful (remaining=1).
- // Iteration 5; bucket by-order:0: Operation successful (remaining=0).
- // Iteration 6; bucket by-order:0: FAILED. Rate limit exceeded.
- // Iteration 7; bucket by-order:0: FAILED. Rate limit exceeded.
- // Iteration 8; bucket by-order:0: FAILED. Rate limit exceeded.
- // Iteration 9; bucket by-order:0: FAILED. Rate limit exceeded.
- // Iteration 10; bucket by-order:1: Operation successful (remaining=5).
- // Iteration 11; bucket by-order:1: Operation successful (remaining=4).
- // Iteration 12; bucket by-order:1: Operation successful (remaining=3).
- // Iteration 13; bucket by-order:1: Operation successful (remaining=2).
- // Iteration 14; bucket by-order:1: Operation successful (remaining=1).
- // Iteration 15; bucket by-order:1: Operation successful (remaining=0).
- // Iteration 16; bucket by-order:1: FAILED. Rate limit exceeded.
- // Iteration 17; bucket by-order:1: FAILED. Rate limit exceeded.
- // Iteration 18; bucket by-order:1: FAILED. Rate limit exceeded.
- // Iteration 19; bucket by-order:1: FAILED. Rate limit exceeded.
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/http_test.go b/vendor/gopkg.in/throttled/throttled.v2/http_test.go
deleted file mode 100644
index 52a706e2d..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/http_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package throttled_test
-
-import (
- "errors"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-type stubLimiter struct {
-}
-
-func (sl *stubLimiter) RateLimit(key string, quantity int) (bool, throttled.RateLimitResult, error) {
- switch key {
- case "limit":
- return true, throttled.RateLimitResult{-1, -1, -1, time.Minute}, nil
- case "error":
- return false, throttled.RateLimitResult{}, errors.New("stubLimiter error")
- default:
- return false, throttled.RateLimitResult{1, 2, time.Minute, -1}, nil
- }
-}
-
-type pathGetter struct{}
-
-func (*pathGetter) Key(r *http.Request) string {
- return r.URL.Path
-}
-
-type httpTestCase struct {
- path string
- code int
- headers map[string]string
-}
-
-func TestHTTPRateLimiter(t *testing.T) {
- limiter := throttled.HTTPRateLimiter{
- RateLimiter: &stubLimiter{},
- VaryBy: &pathGetter{},
- }
-
- handler := limiter.RateLimit(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- }))
-
- runHTTPTestCases(t, handler, []httpTestCase{
- {"ok", 200, map[string]string{"X-Ratelimit-Limit": "1", "X-Ratelimit-Remaining": "2", "X-Ratelimit-Reset": "60"}},
- {"error", 500, map[string]string{}},
- {"limit", 429, map[string]string{"Retry-After": "60"}},
- })
-}
-
-func TestCustomHTTPRateLimiterHandlers(t *testing.T) {
- limiter := throttled.HTTPRateLimiter{
- RateLimiter: &stubLimiter{},
- VaryBy: &pathGetter{},
- DeniedHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "custom limit exceeded", 400)
- }),
- Error: func(w http.ResponseWriter, r *http.Request, err error) {
- http.Error(w, "custom internal error", 501)
- },
- }
-
- handler := limiter.RateLimit(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- }))
-
- runHTTPTestCases(t, handler, []httpTestCase{
- {"limit", 400, map[string]string{}},
- {"error", 501, map[string]string{}},
- })
-}
-
-func runHTTPTestCases(t *testing.T, h http.Handler, cs []httpTestCase) {
- for i, c := range cs {
- req, err := http.NewRequest("GET", c.path, nil)
- if err != nil {
- t.Fatal(err)
- }
-
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, req)
- if have, want := rr.Code, c.code; have != want {
- t.Errorf("Expected request %d at %s to return %d but got %d",
- i, c.path, want, have)
- }
-
- for name, want := range c.headers {
- if have := rr.HeaderMap.Get(name); have != want {
- t.Errorf("Expected request %d at %s to have header '%s: %s' but got '%s'",
- i, c.path, name, want, have)
- }
- }
- }
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/rate.go b/vendor/gopkg.in/throttled/throttled.v2/rate.go
index 649287beb..8c11cdb47 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/rate.go
+++ b/vendor/gopkg.in/throttled/throttled.v2/rate.go
@@ -84,18 +84,17 @@ type Rate struct {
// RateQuota describes the number of requests allowed per time period.
// MaxRate specified the maximum sustained rate of requests and must
-// be greater than zero. MaxBurst defines the number of requests that
+// be greater than zero. MaxBurst defines the number of requests that
// will be allowed to exceed the rate in a single burst and must be
// greater than or equal to zero.
//
// Rate{PerSec(1), 0} would mean that after each request, no more
-// requests will be permitted for that client for one second.
-// Rate{PerSec(2), 0} permits one request per 0.5 seconds rather than
-// two requests in one second. In practice, you probably want to set
-// MaxBurst >0 to provide some flexibility to clients that only need
-// to make a handful of requests. In fact a MaxBurst of zero will
-// *never* permit a request with a quantity greater than one because
-// it will immediately exceed the limit.
+// requests will be permitted for that client for one second. In
+// practice, you probably want to set MaxBurst >0 to provide some
+// flexibility to clients that only need to make a handful of
+// requests. In fact a MaxBurst of zero will *never* permit a request
+// with a quantity greater than one because it will immediately exceed
+// the limit.
type RateQuota struct {
MaxRate Rate
MaxBurst int
@@ -119,12 +118,10 @@ func PerDay(n int) Rate { return Rate{24 * time.Hour / time.Duration(n), n} }
// as for limiting the number of bytes uploaded.
type GCRARateLimiter struct {
limit int
-
// Think of the DVT as our flexibility:
// How far can you deviate from the nominal equally spaced schedule?
// If you like leaky buckets, think about it as the size of your bucket.
delayVariationTolerance time.Duration
-
// Think of the emission interval as the time between events
// in the nominal equally spaced schedule. If you like leaky buckets,
// think of it as how frequently the bucket leaks one unit.
diff --git a/vendor/gopkg.in/throttled/throttled.v2/rate_test.go b/vendor/gopkg.in/throttled/throttled.v2/rate_test.go
deleted file mode 100644
index a1a5f621e..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/rate_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package throttled_test
-
-import (
- "testing"
- "time"
-
- "github.com/throttled/throttled"
- "github.com/throttled/throttled/store/memstore"
-)
-
-const deniedStatus = 429
-
-type testStore struct {
- store throttled.GCRAStore
-
- clock time.Time
- failUpdates bool
-}
-
-func (ts *testStore) GetWithTime(key string) (int64, time.Time, error) {
- v, _, e := ts.store.GetWithTime(key)
- return v, ts.clock, e
-}
-
-func (ts *testStore) SetIfNotExistsWithTTL(key string, value int64, ttl time.Duration) (bool, error) {
- if ts.failUpdates {
- return false, nil
- }
- return ts.store.SetIfNotExistsWithTTL(key, value, ttl)
-}
-
-func (ts *testStore) CompareAndSwapWithTTL(key string, old, new int64, ttl time.Duration) (bool, error) {
- if ts.failUpdates {
- return false, nil
- }
- return ts.store.CompareAndSwapWithTTL(key, old, new, ttl)
-}
-
-func TestRateLimit(t *testing.T) {
- limit := 5
- rq := throttled.RateQuota{throttled.PerSec(1), limit - 1}
- start := time.Unix(0, 0)
- cases := []struct {
- now time.Time
- volume, remaining int
- reset, retry time.Duration
- limited bool
- }{
- // You can never make a request larger than the maximum
- 0: {start, 6, 5, 0, -1, true},
- // Rate limit normal requests appropriately
- 1: {start, 1, 4, time.Second, -1, false},
- 2: {start, 1, 3, 2 * time.Second, -1, false},
- 3: {start, 1, 2, 3 * time.Second, -1, false},
- 4: {start, 1, 1, 4 * time.Second, -1, false},
- 5: {start, 1, 0, 5 * time.Second, -1, false},
- 6: {start, 1, 0, 5 * time.Second, time.Second, true},
- 7: {start.Add(3000 * time.Millisecond), 1, 2, 3000 * time.Millisecond, -1, false},
- 8: {start.Add(3100 * time.Millisecond), 1, 1, 3900 * time.Millisecond, -1, false},
- 9: {start.Add(4000 * time.Millisecond), 1, 1, 4000 * time.Millisecond, -1, false},
- 10: {start.Add(8000 * time.Millisecond), 1, 4, 1000 * time.Millisecond, -1, false},
- 11: {start.Add(9500 * time.Millisecond), 1, 4, 1000 * time.Millisecond, -1, false},
- // Zero-volume request just peeks at the state
- 12: {start.Add(9500 * time.Millisecond), 0, 4, time.Second, -1, false},
- // High-volume request uses up more of the limit
- 13: {start.Add(9500 * time.Millisecond), 2, 2, 3 * time.Second, -1, false},
- // Large requests cannot exceed limits
- 14: {start.Add(9500 * time.Millisecond), 5, 2, 3 * time.Second, 3 * time.Second, true},
- }
-
- mst, err := memstore.New(0)
- if err != nil {
- t.Fatal(err)
- }
- st := testStore{store: mst}
-
- rl, err := throttled.NewGCRARateLimiter(&st, rq)
- if err != nil {
- t.Fatal(err)
- }
-
- // Start the server
- for i, c := range cases {
- st.clock = c.now
-
- limited, context, err := rl.RateLimit("foo", c.volume)
- if err != nil {
- t.Fatalf("%d: %#v", i, err)
- }
-
- if limited != c.limited {
- t.Errorf("%d: expected Limited to be %t but got %t", i, c.limited, limited)
- }
-
- if have, want := context.Limit, limit; have != want {
- t.Errorf("%d: expected Limit to be %d but got %d", i, want, have)
- }
-
- if have, want := context.Remaining, c.remaining; have != want {
- t.Errorf("%d: expected Remaining to be %d but got %d", i, want, have)
- }
-
- if have, want := context.ResetAfter, c.reset; have != want {
- t.Errorf("%d: expected ResetAfter to be %s but got %s", i, want, have)
- }
-
- if have, want := context.RetryAfter, c.retry; have != want {
- t.Errorf("%d: expected RetryAfter to be %d but got %d", i, want, have)
- }
- }
-}
-
-func TestRateLimitUpdateFailures(t *testing.T) {
- rq := throttled.RateQuota{throttled.PerSec(1), 1}
- mst, err := memstore.New(0)
- if err != nil {
- t.Fatal(err)
- }
- st := testStore{store: mst, failUpdates: true}
- rl, err := throttled.NewGCRARateLimiter(&st, rq)
- if err != nil {
- t.Fatal(err)
- }
-
- if _, _, err := rl.RateLimit("foo", 1); err == nil {
- t.Error("Expected limiting to fail when store updates fail")
- }
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/deprecated.go b/vendor/gopkg.in/throttled/throttled.v2/store/deprecated.go
deleted file mode 100644
index 0492ba89e..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/deprecated.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Package store contains deprecated aliases for subpackages
-package store // import "github.com/throttled/throttled/store"
-
-import (
- "github.com/garyburd/redigo/redis"
-
- "github.com/throttled/throttled/store/memstore"
- "github.com/throttled/throttled/store/redigostore"
-)
-
-// DEPRECATED. NewMemStore is a compatible alias for mem.New
-func NewMemStore(maxKeys int) *memstore.MemStore {
- st, err := memstore.New(maxKeys)
- if err != nil {
- // As of this writing, `lru.New` can only return an error if you pass
- // maxKeys <= 0 so this should never occur.
- panic(err)
- }
- return st
-}
-
-// DEPRECATED. NewMemStore is a compatible alias for redis.New
-func NewRedisStore(pool *redis.Pool, keyPrefix string, db int) *redigostore.RedigoStore {
- st, err := redigostore.New(pool, keyPrefix, db)
- if err != nil {
- // As of this writing, creating a Redis store never returns an error
- // so this should be safe while providing some ability to return errors
- // in the future.
- panic(err)
- }
- return st
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore.go b/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore.go
index 352232958..5d8fee8b5 100644
--- a/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore.go
+++ b/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore.go
@@ -1,5 +1,5 @@
// Package memstore offers an in-memory store implementation for throttled.
-package memstore // import "github.com/throttled/throttled/store/memstore"
+package memstore // import "gopkg.in/throttled/throttled.v2/store/memstore"
import (
"sync"
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore_test.go b/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore_test.go
deleted file mode 100644
index 27b1c9b95..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/memstore/memstore_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package memstore_test
-
-import (
- "testing"
-
- "github.com/throttled/throttled/store/memstore"
- "github.com/throttled/throttled/store/storetest"
-)
-
-func TestMemStoreLRU(t *testing.T) {
- st, err := memstore.New(10)
- if err != nil {
- t.Fatal(err)
- }
- storetest.TestGCRAStore(t, st)
-}
-
-func TestMemStoreUnlimited(t *testing.T) {
- st, err := memstore.New(10)
- if err != nil {
- t.Fatal(err)
- }
- storetest.TestGCRAStore(t, st)
-}
-
-func BenchmarkMemStoreLRU(b *testing.B) {
- st, err := memstore.New(10)
- if err != nil {
- b.Fatal(err)
- }
- storetest.BenchmarkGCRAStore(b, st)
-}
-
-func BenchmarkMemStoreUnlimited(b *testing.B) {
- st, err := memstore.New(0)
- if err != nil {
- b.Fatal(err)
- }
- storetest.BenchmarkGCRAStore(b, st)
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore.go b/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore.go
deleted file mode 100644
index 03acbcab0..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore.go
+++ /dev/null
@@ -1,168 +0,0 @@
-// Package redigostore offers Redis-based store implementation for throttled using redigo.
-package redigostore // import "github.com/throttled/throttled/store/redigostore"
-
-import (
- "strings"
- "time"
-
- "github.com/garyburd/redigo/redis"
-)
-
-const (
- redisCASMissingKey = "key does not exist"
- redisCASScript = `
-local v = redis.call('get', KEYS[1])
-if v == false then
- return redis.error_reply("key does not exist")
-end
-if v ~= ARGV[1] then
- return 0
-end
-redis.call('setex', KEYS[1], ARGV[3], ARGV[2])
-return 1
-`
-)
-
-// RedigoStore implements a Redis-based store using redigo.
-type RedigoStore struct {
- pool *redis.Pool
- prefix string
- db int
-}
-
-// New creates a new Redis-based store, using the provided pool to get
-// its connections. The keys will have the specified keyPrefix, which
-// may be an empty string, and the database index specified by db will
-// be selected to store the keys. Any updating operations will reset
-// the key TTL to the provided value rounded down to the nearest
-// second. Depends on Redis 2.6+ for EVAL support.
-func New(pool *redis.Pool, keyPrefix string, db int) (*RedigoStore, error) {
- return &RedigoStore{
- pool: pool,
- prefix: keyPrefix,
- db: db,
- }, nil
-}
-
-// GetWithTime returns the value of the key if it is in the store
-// or -1 if it does not exist. It also returns the current time at
-// the redis server to microsecond precision.
-func (r *RedigoStore) GetWithTime(key string) (int64, time.Time, error) {
- var now time.Time
-
- key = r.prefix + key
-
- conn, err := r.getConn()
- if err != nil {
- return 0, now, err
- }
- defer conn.Close()
-
- conn.Send("TIME")
- conn.Send("GET", key)
- conn.Flush()
- timeReply, err := redis.Values(conn.Receive())
- if err != nil {
- return 0, now, err
- }
-
- var s, us int64
- if _, err := redis.Scan(timeReply, &s, &us); err != nil {
- return 0, now, err
- }
- now = time.Unix(s, us*int64(time.Microsecond))
-
- v, err := redis.Int64(conn.Receive())
- if err == redis.ErrNil {
- return -1, now, nil
- } else if err != nil {
- return 0, now, err
- }
-
- return v, now, nil
-}
-
-// SetIfNotExistsWithTTL sets the value of key only if it is not
-// already set in the store it returns whether a new value was set.
-// If a new value was set, the ttl in the key is also set, though this
-// operation is not performed atomically.
-func (r *RedigoStore) SetIfNotExistsWithTTL(key string, value int64, ttl time.Duration) (bool, error) {
- key = r.prefix + key
-
- conn, err := r.getConn()
- if err != nil {
- return false, err
- }
- defer conn.Close()
-
- v, err := redis.Int64(conn.Do("SETNX", key, value))
- if err != nil {
- return false, err
- }
-
- updated := v == 1
-
- ttlSeconds := int(ttl.Seconds())
-
- // An `EXPIRE 0` will delete the key immediately, so make sure that we set
- // expiry for a minimum of one second out so that our results stay in the
- // store.
- if ttlSeconds < 1 {
- ttlSeconds = 1
- }
-
- if _, err := conn.Do("EXPIRE", key, ttlSeconds); err != nil {
- return updated, err
- }
-
- return updated, nil
-}
-
-// CompareAndSwapWithTTL atomically compares the value at key to the
-// old value. If it matches, it sets it to the new value and returns
-// true. Otherwise, it returns false. If the key does not exist in the
-// store, it returns false with no error. If the swap succeeds, the
-// ttl for the key is updated atomically.
-func (r *RedigoStore) CompareAndSwapWithTTL(key string, old, new int64, ttl time.Duration) (bool, error) {
- key = r.prefix + key
- conn, err := r.getConn()
- if err != nil {
- return false, err
- }
- defer conn.Close()
-
- ttlSeconds := int(ttl.Seconds())
-
- // An `EXPIRE 0` will delete the key immediately, so make sure that we set
- // expiry for a minimum of one second out so that our results stay in the
- // store.
- if ttlSeconds < 1 {
- ttlSeconds = 1
- }
-
- swapped, err := redis.Bool(conn.Do("EVAL", redisCASScript, 1, key, old, new, ttlSeconds))
- if err != nil {
- if strings.Contains(err.Error(), redisCASMissingKey) {
- return false, nil
- }
-
- return false, err
- }
-
- return swapped, nil
-}
-
-// Select the specified database index.
-func (r *RedigoStore) getConn() (redis.Conn, error) {
- conn := r.pool.Get()
-
- // Select the specified database
- if r.db > 0 {
- if _, err := redis.String(conn.Do("SELECT", r.db)); err != nil {
- conn.Close()
- return nil, err
- }
- }
-
- return conn, nil
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore_test.go b/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore_test.go
deleted file mode 100644
index ee9e2904d..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/redigostore/redigostore_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package redigostore_test
-
-import (
- "testing"
- "time"
-
- "github.com/garyburd/redigo/redis"
-
- "github.com/throttled/throttled/store/redigostore"
- "github.com/throttled/throttled/store/storetest"
-)
-
-const (
- redisTestDB = 1
- redisTestPrefix = "throttled:"
-)
-
-func getPool() *redis.Pool {
- pool := &redis.Pool{
- MaxIdle: 3,
- IdleTimeout: 30 * time.Second,
- Dial: func() (redis.Conn, error) {
- return redis.Dial("tcp", ":6379")
- },
- TestOnBorrow: func(c redis.Conn, t time.Time) error {
- _, err := c.Do("PING")
- return err
- },
- }
- return pool
-}
-
-func TestRedisStore(t *testing.T) {
- c, st := setupRedis(t, 0)
- defer c.Close()
- defer clearRedis(c)
-
- clearRedis(c)
- storetest.TestGCRAStore(t, st)
- storetest.TestGCRAStoreTTL(t, st)
-}
-
-func BenchmarkRedisStore(b *testing.B) {
- c, st := setupRedis(b, 0)
- defer c.Close()
- defer clearRedis(c)
-
- storetest.BenchmarkGCRAStore(b, st)
-}
-
-func clearRedis(c redis.Conn) error {
- keys, err := redis.Values(c.Do("KEYS", redisTestPrefix+"*"))
- if err != nil {
- return err
- }
-
- if _, err := redis.Int(c.Do("DEL", keys...)); err != nil {
- return err
- }
-
- return nil
-}
-
-func setupRedis(tb testing.TB, ttl time.Duration) (redis.Conn, *redigostore.RedigoStore) {
- pool := getPool()
- c := pool.Get()
-
- if _, err := redis.String(c.Do("PING")); err != nil {
- c.Close()
- tb.Skip("redis server not available on localhost port 6379")
- }
-
- if _, err := redis.String(c.Do("SELECT", redisTestDB)); err != nil {
- c.Close()
- tb.Fatal(err)
- }
-
- st, err := redigostore.New(pool, redisTestPrefix, redisTestDB)
- if err != nil {
- c.Close()
- tb.Fatal(err)
- }
-
- return c, st
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/storetest/doc.go b/vendor/gopkg.in/throttled/throttled.v2/store/storetest/doc.go
deleted file mode 100644
index 405c59a12..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/storetest/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package storetest provides a helper for testing throttled stores.
-package storetest // import "github.com/throttled/throttled/store/storetest"
diff --git a/vendor/gopkg.in/throttled/throttled.v2/store/storetest/storetest.go b/vendor/gopkg.in/throttled/throttled.v2/store/storetest/storetest.go
deleted file mode 100644
index 2233ebdfb..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/store/storetest/storetest.go
+++ /dev/null
@@ -1,176 +0,0 @@
-// Package storetest provides a helper for testing throttled stores.
-package storetest // import "github.com/throttled/throttled/store/storetest"
-
-import (
- "math/rand"
- "strconv"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-// TestGCRAStore tests the behavior of a GCRAStore implementation for
-// compliance with the throttled API. It does not require support
-// for TTLs.
-func TestGCRAStore(t *testing.T, st throttled.GCRAStore) {
- // GetWithTime a missing key
- if have, _, err := st.GetWithTime("foo"); err != nil {
- t.Fatal(err)
- } else if have != -1 {
- t.Errorf("expected GetWithTime to return -1 for a missing key but got %d", have)
- }
-
- // SetIfNotExists on a new key
- want := int64(1)
-
- if set, err := st.SetIfNotExistsWithTTL("foo", want, 0); err != nil {
- t.Fatal(err)
- } else if !set {
- t.Errorf("expected SetIfNotExists on an empty key to succeed")
- }
-
- before := time.Now()
-
- if have, now, err := st.GetWithTime("foo"); err != nil {
- t.Fatal(err)
- } else if have != want {
- t.Errorf("expected GetWithTime to return %d but got %d", want, have)
- } else if now.UnixNano() <= 0 {
- t.Errorf("expected GetWithTime to return a time representable representable as a positive int64 of nanoseconds since the epoch")
- } else if now.Before(before) || now.After(time.Now()) {
- // Note that we make the assumption here that the store is running on
- // the same machine as this test and thus shares a clock. This can be a
- // little tricky in the case of Redis, which could be running
- // elsewhere. The test assumes that it's running either locally on on
- // Travis (where currently the Redis is available on localhost). If new
- // test environments are procured, this may need to be revisited.
- t.Errorf("expected GetWithTime to return a time between the time before the call and the time after the call")
- }
-
- // SetIfNotExists on an existing key
- if set, err := st.SetIfNotExistsWithTTL("foo", 123, 0); err != nil {
- t.Fatal(err)
- } else if set {
- t.Errorf("expected SetIfNotExists on an existing key to fail")
- }
-
- if have, _, err := st.GetWithTime("foo"); err != nil {
- t.Fatal(err)
- } else if have != want {
- t.Errorf("expected GetWithTime to return %d but got %d", want, have)
- }
-
- // SetIfNotExists on a different key
- if set, err := st.SetIfNotExistsWithTTL("bar", 456, 0); err != nil {
- t.Fatal(err)
- } else if !set {
- t.Errorf("expected SetIfNotExists on an empty key to succeed")
- }
-
- // Returns the false on a missing key
- if swapped, err := st.CompareAndSwapWithTTL("baz", 1, 2, 0); err != nil {
- t.Fatal(err)
- } else if swapped {
- t.Errorf("expected CompareAndSwap to fail on a missing key")
- }
-
- // Test a successful CAS
- want = int64(2)
-
- if swapped, err := st.CompareAndSwapWithTTL("foo", 1, want, 0); err != nil {
- t.Fatal(err)
- } else if !swapped {
- t.Errorf("expected CompareAndSwap to succeed")
- }
-
- if have, _, err := st.GetWithTime("foo"); err != nil {
- t.Fatal(err)
- } else if have != want {
- t.Errorf("expected GetWithTime to return %d but got %d", want, have)
- }
-
- // Test an unsuccessful CAS
- if swapped, err := st.CompareAndSwapWithTTL("foo", 1, 2, 0); err != nil {
- t.Fatal(err)
- } else if swapped {
- t.Errorf("expected CompareAndSwap to fail")
- }
-
- if have, _, err := st.GetWithTime("foo"); err != nil {
- t.Fatal(err)
- } else if have != want {
- t.Errorf("expected GetWithTime to return %d but got %d", want, have)
- }
-}
-
-// TestGCRAStoreTTL tests the behavior of TTLs in a GCRAStore implementation.
-func TestGCRAStoreTTL(t *testing.T, st throttled.GCRAStore) {
- ttl := time.Second
- want := int64(1)
- key := "ttl"
-
- if _, err := st.SetIfNotExistsWithTTL(key, want, ttl); err != nil {
- t.Fatal(err)
- }
-
- if have, _, err := st.GetWithTime(key); err != nil {
- t.Fatal(err)
- } else if have != want {
- t.Errorf("expected GetWithTime to return %d, got %d", want, have)
- }
-
- // I can't think of a generic way to test expiration without a sleep
- time.Sleep(ttl + time.Millisecond)
-
- if have, _, err := st.GetWithTime(key); err != nil {
- t.Fatal(err)
- } else if have != -1 {
- t.Errorf("expected GetWithTime to fail on an expired key but got %d", have)
- }
-}
-
-// BenchmarkGCRAStore runs parallel benchmarks against a GCRAStore implementation.
-// Aside from being useful for performance testing, this is useful for finding
-// race conditions with the Go race detector.
-func BenchmarkGCRAStore(b *testing.B, st throttled.GCRAStore) {
- seed := int64(42)
- var attempts, updates int64
-
- b.RunParallel(func(pb *testing.PB) {
- // We need atomic behavior around the RNG or go detects a race in the test
- delta := int64(1)
- seedValue := atomic.AddInt64(&seed, delta) - delta
- gen := rand.New(rand.NewSource(seedValue))
-
- for pb.Next() {
- key := strconv.FormatInt(gen.Int63n(50), 10)
-
- var v int64
- var updated bool
-
- v, _, err := st.GetWithTime(key)
- if v == -1 {
- updated, err = st.SetIfNotExistsWithTTL(key, gen.Int63(), 0)
- if err != nil {
- b.Error(err)
- }
- } else if err != nil {
- b.Error(err)
- } else {
- updated, err = st.CompareAndSwapWithTTL(key, v, gen.Int63(), 0)
- if err != nil {
- b.Error(err)
- }
- }
-
- atomic.AddInt64(&attempts, 1)
- if updated {
- atomic.AddInt64(&updates, 1)
- }
- }
- })
-
- b.Logf("%d/%d update operations succeeed", updates, attempts)
-}
diff --git a/vendor/gopkg.in/throttled/throttled.v2/varyby_test.go b/vendor/gopkg.in/throttled/throttled.v2/varyby_test.go
deleted file mode 100644
index 6ad48ea19..000000000
--- a/vendor/gopkg.in/throttled/throttled.v2/varyby_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package throttled_test
-
-import (
- "net/http"
- "net/url"
- "testing"
-
- "github.com/throttled/throttled"
-)
-
-func TestVaryBy(t *testing.T) {
- u, err := url.Parse("http://localhost/test/path?q=s")
- if err != nil {
- panic(err)
- }
- ck := &http.Cookie{Name: "ssn", Value: "test"}
- cases := []struct {
- vb *throttled.VaryBy
- r *http.Request
- k string
- }{
- 0: {nil, &http.Request{}, ""},
- 1: {&throttled.VaryBy{RemoteAddr: true}, &http.Request{RemoteAddr: "::"}, "::\n"},
- 2: {
- &throttled.VaryBy{Method: true, Path: true},
- &http.Request{Method: "POST", URL: u},
- "post\n/test/path\n",
- },
- 3: {
- &throttled.VaryBy{Headers: []string{"Content-length"}},
- &http.Request{Header: http.Header{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"123"}}},
- "123\n",
- },
- 4: {
- &throttled.VaryBy{Separator: ",", Method: true, Headers: []string{"Content-length"}, Params: []string{"q", "user"}},
- &http.Request{Method: "GET", Header: http.Header{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"123"}}, Form: url.Values{"q": []string{"s"}, "pwd": []string{"secret"}, "user": []string{"test"}}},
- "get,123,s,test,",
- },
- 5: {
- &throttled.VaryBy{Cookies: []string{"ssn"}},
- &http.Request{Header: http.Header{"Cookie": []string{ck.String()}}},
- "test\n",
- },
- 6: {
- &throttled.VaryBy{Cookies: []string{"ssn"}, RemoteAddr: true, Custom: func(r *http.Request) string {
- return "blah"
- }},
- &http.Request{Header: http.Header{"Cookie": []string{ck.String()}}},
- "blah",
- },
- }
- for i, c := range cases {
- got := c.vb.Key(c.r)
- if got != c.k {
- t.Errorf("%d: expected '%s' (%d), got '%s' (%d)", i, c.k, len(c.k), got, len(got))
- }
- }
-}
diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml
index 004172a2e..9f556934d 100644
--- a/vendor/gopkg.in/yaml.v2/.travis.yml
+++ b/vendor/gopkg.in/yaml.v2/.travis.yml
@@ -4,6 +4,9 @@ go:
- 1.4
- 1.5
- 1.6
+ - 1.7
+ - 1.8
+ - 1.9
- tip
go_import_path: gopkg.in/yaml.v2
diff --git a/vendor/gopkg.in/yaml.v2/NOTICE b/vendor/gopkg.in/yaml.v2/NOTICE
new file mode 100644
index 000000000..866d74a7a
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/NOTICE
@@ -0,0 +1,13 @@
+Copyright 2011-2016 Canonical Ltd.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/vendor/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md
index 2ed3314c7..b50c6e877 100644
--- a/vendor/gopkg.in/yaml.v2/README.md
+++ b/vendor/gopkg.in/yaml.v2/README.md
@@ -48,8 +48,6 @@ The yaml package is licensed under the Apache License 2.0. Please see the LICENS
Example
-------
-Some more examples can be found in the "examples" folder.
-
```Go
package main
diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go
index 95ec014e8..1f7e87e67 100644
--- a/vendor/gopkg.in/yaml.v2/apic.go
+++ b/vendor/gopkg.in/yaml.v2/apic.go
@@ -2,7 +2,6 @@ package yaml
import (
"io"
- "os"
)
func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) {
@@ -48,9 +47,9 @@ func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err
return n, nil
}
-// File read handler.
-func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
- return parser.input_file.Read(buffer)
+// Reader read handler.
+func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
+ return parser.input_reader.Read(buffer)
}
// Set a string input.
@@ -64,12 +63,12 @@ func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) {
}
// Set a file input.
-func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) {
+func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) {
if parser.read_handler != nil {
panic("must set the input source only once")
}
- parser.read_handler = yaml_file_read_handler
- parser.input_file = file
+ parser.read_handler = yaml_reader_read_handler
+ parser.input_reader = r
}
// Set the source encoding.
@@ -81,14 +80,13 @@ func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) {
}
// Create a new emitter object.
-func yaml_emitter_initialize(emitter *yaml_emitter_t) bool {
+func yaml_emitter_initialize(emitter *yaml_emitter_t) {
*emitter = yaml_emitter_t{
buffer: make([]byte, output_buffer_size),
raw_buffer: make([]byte, 0, output_raw_buffer_size),
states: make([]yaml_emitter_state_t, 0, initial_stack_size),
events: make([]yaml_event_t, 0, initial_queue_size),
}
- return true
}
// Destroy an emitter object.
@@ -102,9 +100,10 @@ func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
return nil
}
-// File write handler.
-func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
- _, err := emitter.output_file.Write(buffer)
+// yaml_writer_write_handler uses emitter.output_writer to write the
+// emitted text.
+func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
+ _, err := emitter.output_writer.Write(buffer)
return err
}
@@ -118,12 +117,12 @@ func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]by
}
// Set a file output.
-func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) {
+func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) {
if emitter.write_handler != nil {
panic("must set the output target only once")
}
- emitter.write_handler = yaml_file_write_handler
- emitter.output_file = file
+ emitter.write_handler = yaml_writer_write_handler
+ emitter.output_writer = w
}
// Set the output encoding.
@@ -252,41 +251,41 @@ func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) {
//
// Create STREAM-START.
-func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool {
+func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) {
*event = yaml_event_t{
typ: yaml_STREAM_START_EVENT,
encoding: encoding,
}
- return true
}
// Create STREAM-END.
-func yaml_stream_end_event_initialize(event *yaml_event_t) bool {
+func yaml_stream_end_event_initialize(event *yaml_event_t) {
*event = yaml_event_t{
typ: yaml_STREAM_END_EVENT,
}
- return true
}
// Create DOCUMENT-START.
-func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t,
- tag_directives []yaml_tag_directive_t, implicit bool) bool {
+func yaml_document_start_event_initialize(
+ event *yaml_event_t,
+ version_directive *yaml_version_directive_t,
+ tag_directives []yaml_tag_directive_t,
+ implicit bool,
+) {
*event = yaml_event_t{
typ: yaml_DOCUMENT_START_EVENT,
version_directive: version_directive,
tag_directives: tag_directives,
implicit: implicit,
}
- return true
}
// Create DOCUMENT-END.
-func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool {
+func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) {
*event = yaml_event_t{
typ: yaml_DOCUMENT_END_EVENT,
implicit: implicit,
}
- return true
}
///*
@@ -348,7 +347,7 @@ func yaml_sequence_end_event_initialize(event *yaml_event_t) bool {
}
// Create MAPPING-START.
-func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool {
+func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) {
*event = yaml_event_t{
typ: yaml_MAPPING_START_EVENT,
anchor: anchor,
@@ -356,15 +355,13 @@ func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte
implicit: implicit,
style: yaml_style_t(style),
}
- return true
}
// Create MAPPING-END.
-func yaml_mapping_end_event_initialize(event *yaml_event_t) bool {
+func yaml_mapping_end_event_initialize(event *yaml_event_t) {
*event = yaml_event_t{
typ: yaml_MAPPING_END_EVENT,
}
- return true
}
// Destroy an event object.
@@ -471,7 +468,7 @@ func yaml_event_delete(event *yaml_event_t) {
// } context
// tag_directive *yaml_tag_directive_t
//
-// context.error = YAML_NO_ERROR // Eliminate a compliler warning.
+// context.error = YAML_NO_ERROR // Eliminate a compiler warning.
//
// assert(document) // Non-NULL document object is expected.
//
diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go
index e85eb2e3f..e4e56e28e 100644
--- a/vendor/gopkg.in/yaml.v2/decode.go
+++ b/vendor/gopkg.in/yaml.v2/decode.go
@@ -4,6 +4,7 @@ import (
"encoding"
"encoding/base64"
"fmt"
+ "io"
"math"
"reflect"
"strconv"
@@ -22,19 +23,22 @@ type node struct {
kind int
line, column int
tag string
- value string
- implicit bool
- children []*node
- anchors map[string]*node
+ // For an alias node, alias holds the resolved alias.
+ alias *node
+ value string
+ implicit bool
+ children []*node
+ anchors map[string]*node
}
// ----------------------------------------------------------------------------
// Parser, produces a node tree out of a libyaml event stream.
type parser struct {
- parser yaml_parser_t
- event yaml_event_t
- doc *node
+ parser yaml_parser_t
+ event yaml_event_t
+ doc *node
+ doneInit bool
}
func newParser(b []byte) *parser {
@@ -42,21 +46,30 @@ func newParser(b []byte) *parser {
if !yaml_parser_initialize(&p.parser) {
panic("failed to initialize YAML emitter")
}
-
if len(b) == 0 {
b = []byte{'\n'}
}
-
yaml_parser_set_input_string(&p.parser, b)
+ return &p
+}
- p.skip()
- if p.event.typ != yaml_STREAM_START_EVENT {
- panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
+func newParserFromReader(r io.Reader) *parser {
+ p := parser{}
+ if !yaml_parser_initialize(&p.parser) {
+ panic("failed to initialize YAML emitter")
}
- p.skip()
+ yaml_parser_set_input_reader(&p.parser, r)
return &p
}
+func (p *parser) init() {
+ if p.doneInit {
+ return
+ }
+ p.expect(yaml_STREAM_START_EVENT)
+ p.doneInit = true
+}
+
func (p *parser) destroy() {
if p.event.typ != yaml_NO_EVENT {
yaml_event_delete(&p.event)
@@ -64,16 +77,35 @@ func (p *parser) destroy() {
yaml_parser_delete(&p.parser)
}
-func (p *parser) skip() {
- if p.event.typ != yaml_NO_EVENT {
- if p.event.typ == yaml_STREAM_END_EVENT {
- failf("attempted to go past the end of stream; corrupted value?")
+// expect consumes an event from the event stream and
+// checks that it's of the expected type.
+func (p *parser) expect(e yaml_event_type_t) {
+ if p.event.typ == yaml_NO_EVENT {
+ if !yaml_parser_parse(&p.parser, &p.event) {
+ p.fail()
}
- yaml_event_delete(&p.event)
+ }
+ if p.event.typ == yaml_STREAM_END_EVENT {
+ failf("attempted to go past the end of stream; corrupted value?")
+ }
+ if p.event.typ != e {
+ p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ)
+ p.fail()
+ }
+ yaml_event_delete(&p.event)
+ p.event.typ = yaml_NO_EVENT
+}
+
+// peek peeks at the next event in the event stream,
+// puts the results into p.event and returns the event type.
+func (p *parser) peek() yaml_event_type_t {
+ if p.event.typ != yaml_NO_EVENT {
+ return p.event.typ
}
if !yaml_parser_parse(&p.parser, &p.event) {
p.fail()
}
+ return p.event.typ
}
func (p *parser) fail() {
@@ -81,6 +113,10 @@ func (p *parser) fail() {
var line int
if p.parser.problem_mark.line != 0 {
line = p.parser.problem_mark.line
+ // Scanner errors don't iterate line before returning error
+ if p.parser.error == yaml_SCANNER_ERROR {
+ line++
+ }
} else if p.parser.context_mark.line != 0 {
line = p.parser.context_mark.line
}
@@ -103,7 +139,8 @@ func (p *parser) anchor(n *node, anchor []byte) {
}
func (p *parser) parse() *node {
- switch p.event.typ {
+ p.init()
+ switch p.peek() {
case yaml_SCALAR_EVENT:
return p.scalar()
case yaml_ALIAS_EVENT:
@@ -118,7 +155,7 @@ func (p *parser) parse() *node {
// Happens when attempting to decode an empty buffer.
return nil
default:
- panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ)))
+ panic("attempted to parse unknown event: " + p.event.typ.String())
}
}
@@ -134,19 +171,20 @@ func (p *parser) document() *node {
n := p.node(documentNode)
n.anchors = make(map[string]*node)
p.doc = n
- p.skip()
+ p.expect(yaml_DOCUMENT_START_EVENT)
n.children = append(n.children, p.parse())
- if p.event.typ != yaml_DOCUMENT_END_EVENT {
- panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ)))
- }
- p.skip()
+ p.expect(yaml_DOCUMENT_END_EVENT)
return n
}
func (p *parser) alias() *node {
n := p.node(aliasNode)
n.value = string(p.event.anchor)
- p.skip()
+ n.alias = p.doc.anchors[n.value]
+ if n.alias == nil {
+ failf("unknown anchor '%s' referenced", n.value)
+ }
+ p.expect(yaml_ALIAS_EVENT)
return n
}
@@ -156,29 +194,29 @@ func (p *parser) scalar() *node {
n.tag = string(p.event.tag)
n.implicit = p.event.implicit
p.anchor(n, p.event.anchor)
- p.skip()
+ p.expect(yaml_SCALAR_EVENT)
return n
}
func (p *parser) sequence() *node {
n := p.node(sequenceNode)
p.anchor(n, p.event.anchor)
- p.skip()
- for p.event.typ != yaml_SEQUENCE_END_EVENT {
+ p.expect(yaml_SEQUENCE_START_EVENT)
+ for p.peek() != yaml_SEQUENCE_END_EVENT {
n.children = append(n.children, p.parse())
}
- p.skip()
+ p.expect(yaml_SEQUENCE_END_EVENT)
return n
}
func (p *parser) mapping() *node {
n := p.node(mappingNode)
p.anchor(n, p.event.anchor)
- p.skip()
- for p.event.typ != yaml_MAPPING_END_EVENT {
+ p.expect(yaml_MAPPING_START_EVENT)
+ for p.peek() != yaml_MAPPING_END_EVENT {
n.children = append(n.children, p.parse(), p.parse())
}
- p.skip()
+ p.expect(yaml_MAPPING_END_EVENT)
return n
}
@@ -187,7 +225,7 @@ func (p *parser) mapping() *node {
type decoder struct {
doc *node
- aliases map[string]bool
+ aliases map[*node]bool
mapType reflect.Type
terrors []string
strict bool
@@ -198,11 +236,13 @@ var (
durationType = reflect.TypeOf(time.Duration(0))
defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
ifaceType = defaultMapType.Elem()
+ timeType = reflect.TypeOf(time.Time{})
+ ptrTimeType = reflect.TypeOf(&time.Time{})
)
func newDecoder(strict bool) *decoder {
d := &decoder{mapType: defaultMapType, strict: strict}
- d.aliases = make(map[string]bool)
+ d.aliases = make(map[*node]bool)
return d
}
@@ -308,16 +348,13 @@ func (d *decoder) document(n *node, out reflect.Value) (good bool) {
}
func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
- an, ok := d.doc.anchors[n.value]
- if !ok {
- failf("unknown anchor '%s' referenced", n.value)
- }
- if d.aliases[n.value] {
+ if d.aliases[n] {
+ // TODO this could actually be allowed in some circumstances.
failf("anchor '%s' value contains itself", n.value)
}
- d.aliases[n.value] = true
- good = d.unmarshal(an, out)
- delete(d.aliases, n.value)
+ d.aliases[n] = true
+ good = d.unmarshal(n.alias, out)
+ delete(d.aliases, n)
return good
}
@@ -329,7 +366,7 @@ func resetMap(out reflect.Value) {
}
}
-func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
+func (d *decoder) scalar(n *node, out reflect.Value) bool {
var tag string
var resolved interface{}
if n.tag == "" && !n.implicit {
@@ -353,9 +390,26 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
}
return true
}
- if s, ok := resolved.(string); ok && out.CanAddr() {
- if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok {
- err := u.UnmarshalText([]byte(s))
+ if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
+ // We've resolved to exactly the type we want, so use that.
+ out.Set(resolvedv)
+ return true
+ }
+ // Perhaps we can use the value as a TextUnmarshaler to
+ // set its value.
+ if out.CanAddr() {
+ u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
+ if ok {
+ var text []byte
+ if tag == yaml_BINARY_TAG {
+ text = []byte(resolved.(string))
+ } else {
+ // We let any value be unmarshaled into TextUnmarshaler.
+ // That might be more lax than we'd like, but the
+ // TextUnmarshaler itself should bowl out any dubious values.
+ text = []byte(n.value)
+ }
+ err := u.UnmarshalText(text)
if err != nil {
fail(err)
}
@@ -366,46 +420,54 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
case reflect.String:
if tag == yaml_BINARY_TAG {
out.SetString(resolved.(string))
- good = true
- } else if resolved != nil {
+ return true
+ }
+ if resolved != nil {
out.SetString(n.value)
- good = true
+ return true
}
case reflect.Interface:
if resolved == nil {
out.Set(reflect.Zero(out.Type()))
+ } else if tag == yaml_TIMESTAMP_TAG {
+ // It looks like a timestamp but for backward compatibility
+ // reasons we set it as a string, so that code that unmarshals
+ // timestamp-like values into interface{} will continue to
+ // see a string and not a time.Time.
+ // TODO(v3) Drop this.
+ out.Set(reflect.ValueOf(n.value))
} else {
out.Set(reflect.ValueOf(resolved))
}
- good = true
+ return true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch resolved := resolved.(type) {
case int:
if !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
- good = true
+ return true
}
case int64:
if !out.OverflowInt(resolved) {
out.SetInt(resolved)
- good = true
+ return true
}
case uint64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
- good = true
+ return true
}
case float64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
- good = true
+ return true
}
case string:
if out.Type() == durationType {
d, err := time.ParseDuration(resolved)
if err == nil {
out.SetInt(int64(d))
- good = true
+ return true
}
}
}
@@ -414,44 +476,49 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
case int:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
- good = true
+ return true
}
case int64:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
- good = true
+ return true
}
case uint64:
if !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
- good = true
+ return true
}
case float64:
if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
- good = true
+ return true
}
}
case reflect.Bool:
switch resolved := resolved.(type) {
case bool:
out.SetBool(resolved)
- good = true
+ return true
}
case reflect.Float32, reflect.Float64:
switch resolved := resolved.(type) {
case int:
out.SetFloat(float64(resolved))
- good = true
+ return true
case int64:
out.SetFloat(float64(resolved))
- good = true
+ return true
case uint64:
out.SetFloat(float64(resolved))
- good = true
+ return true
case float64:
out.SetFloat(resolved)
- good = true
+ return true
+ }
+ case reflect.Struct:
+ if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
+ out.Set(resolvedv)
+ return true
}
case reflect.Ptr:
if out.Type().Elem() == reflect.TypeOf(resolved) {
@@ -459,13 +526,11 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
elem := reflect.New(out.Type().Elem())
elem.Elem().Set(reflect.ValueOf(resolved))
out.Set(elem)
- good = true
+ return true
}
}
- if !good {
- d.terror(n, tag, out)
- }
- return good
+ d.terror(n, tag, out)
+ return false
}
func settableValueOf(i interface{}) reflect.Value {
@@ -482,6 +547,10 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
switch out.Kind() {
case reflect.Slice:
out.Set(reflect.MakeSlice(out.Type(), l, l))
+ case reflect.Array:
+ if l != out.Len() {
+ failf("invalid array: want %d elements but got %d", out.Len(), l)
+ }
case reflect.Interface:
// No type hints. Will have to use a generic sequence.
iface = out
@@ -500,7 +569,9 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
j++
}
}
- out.Set(out.Slice(0, j))
+ if out.Kind() != reflect.Array {
+ out.Set(out.Slice(0, j))
+ }
if iface.IsValid() {
iface.Set(out)
}
@@ -561,7 +632,7 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
}
e := reflect.New(et).Elem()
if d.unmarshal(n.children[i+1], e) {
- out.SetMapIndex(k, e)
+ d.setMapIndex(n.children[i+1], out, k, e)
}
}
}
@@ -569,6 +640,14 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
return true
}
+func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) {
+ if d.strict && out.MapIndex(k) != zeroValue {
+ d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface()))
+ return
+ }
+ out.SetMapIndex(k, v)
+}
+
func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
outt := out.Type()
if outt.Elem() != mapItemType {
@@ -616,6 +695,10 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
elemType = inlineMap.Type().Elem()
}
+ var doneFields []bool
+ if d.strict {
+ doneFields = make([]bool, len(sinfo.FieldsList))
+ }
for i := 0; i < l; i += 2 {
ni := n.children[i]
if isMerge(ni) {
@@ -626,6 +709,13 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
continue
}
if info, ok := sinfo.FieldsMap[name.String()]; ok {
+ if d.strict {
+ if doneFields[info.Id] {
+ d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type()))
+ continue
+ }
+ doneFields[info.Id] = true
+ }
var field reflect.Value
if info.Inline == nil {
field = out.Field(info.Num)
@@ -639,9 +729,9 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
}
value := reflect.New(elemType).Elem()
d.unmarshal(n.children[i+1], value)
- inlineMap.SetMapIndex(name, value)
+ d.setMapIndex(n.children[i+1], inlineMap, name, value)
} else if d.strict {
- d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in struct %s", ni.line+1, name.String(), out.Type()))
+ d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type()))
}
}
return true
diff --git a/vendor/gopkg.in/yaml.v2/decode_test.go b/vendor/gopkg.in/yaml.v2/decode_test.go
deleted file mode 100644
index e5366c261..000000000
--- a/vendor/gopkg.in/yaml.v2/decode_test.go
+++ /dev/null
@@ -1,1032 +0,0 @@
-package yaml_test
-
-import (
- "errors"
- . "gopkg.in/check.v1"
- "gopkg.in/yaml.v2"
- "math"
- "net"
- "reflect"
- "strings"
- "time"
-)
-
-var unmarshalIntTest = 123
-
-var unmarshalTests = []struct {
- data string
- value interface{}
-}{
- {
- "",
- &struct{}{},
- }, {
- "{}", &struct{}{},
- }, {
- "v: hi",
- map[string]string{"v": "hi"},
- }, {
- "v: hi", map[string]interface{}{"v": "hi"},
- }, {
- "v: true",
- map[string]string{"v": "true"},
- }, {
- "v: true",
- map[string]interface{}{"v": true},
- }, {
- "v: 10",
- map[string]interface{}{"v": 10},
- }, {
- "v: 0b10",
- map[string]interface{}{"v": 2},
- }, {
- "v: 0xA",
- map[string]interface{}{"v": 10},
- }, {
- "v: 4294967296",
- map[string]int64{"v": 4294967296},
- }, {
- "v: 0.1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .Inf",
- map[string]interface{}{"v": math.Inf(+1)},
- }, {
- "v: -.Inf",
- map[string]interface{}{"v": math.Inf(-1)},
- }, {
- "v: -10",
- map[string]interface{}{"v": -10},
- }, {
- "v: -.1",
- map[string]interface{}{"v": -0.1},
- },
-
- // Simple values.
- {
- "123",
- &unmarshalIntTest,
- },
-
- // Floats from spec
- {
- "canonical: 6.8523e+5",
- map[string]interface{}{"canonical": 6.8523e+5},
- }, {
- "expo: 685.230_15e+03",
- map[string]interface{}{"expo": 685.23015e+03},
- }, {
- "fixed: 685_230.15",
- map[string]interface{}{"fixed": 685230.15},
- }, {
- "neginf: -.inf",
- map[string]interface{}{"neginf": math.Inf(-1)},
- }, {
- "fixed: 685_230.15",
- map[string]float64{"fixed": 685230.15},
- },
- //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported
- //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails.
-
- // Bools from spec
- {
- "canonical: y",
- map[string]interface{}{"canonical": true},
- }, {
- "answer: NO",
- map[string]interface{}{"answer": false},
- }, {
- "logical: True",
- map[string]interface{}{"logical": true},
- }, {
- "option: on",
- map[string]interface{}{"option": true},
- }, {
- "option: on",
- map[string]bool{"option": true},
- },
- // Ints from spec
- {
- "canonical: 685230",
- map[string]interface{}{"canonical": 685230},
- }, {
- "decimal: +685_230",
- map[string]interface{}{"decimal": 685230},
- }, {
- "octal: 02472256",
- map[string]interface{}{"octal": 685230},
- }, {
- "hexa: 0x_0A_74_AE",
- map[string]interface{}{"hexa": 685230},
- }, {
- "bin: 0b1010_0111_0100_1010_1110",
- map[string]interface{}{"bin": 685230},
- }, {
- "bin: -0b101010",
- map[string]interface{}{"bin": -42},
- }, {
- "decimal: +685_230",
- map[string]int{"decimal": 685230},
- },
-
- //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported
-
- // Nulls from spec
- {
- "empty:",
- map[string]interface{}{"empty": nil},
- }, {
- "canonical: ~",
- map[string]interface{}{"canonical": nil},
- }, {
- "english: null",
- map[string]interface{}{"english": nil},
- }, {
- "~: null key",
- map[interface{}]string{nil: "null key"},
- }, {
- "empty:",
- map[string]*bool{"empty": nil},
- },
-
- // Flow sequence
- {
- "seq: [A,B]",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq: [A,B,C,]",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq: [A,1,C]",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
- // Block sequence
- {
- "seq:\n - A\n - B",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq:\n - A\n - B\n - C",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
-
- // Literal block scalar
- {
- "scalar: | # Comment\n\n literal\n\n \ttext\n\n",
- map[string]string{"scalar": "\nliteral\n\n\ttext\n"},
- },
-
- // Folded block scalar
- {
- "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n",
- map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"},
- },
-
- // Map inside interface with no type hints.
- {
- "a: {b: c}",
- map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- },
-
- // Structs and type conversions.
- {
- "hello: world",
- &struct{ Hello string }{"world"},
- }, {
- "a: {b: c}",
- &struct{ A struct{ B string } }{struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A *struct{ B string } }{&struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A map[string]string }{map[string]string{"b": "c"}},
- }, {
- "a: {b: c}",
- &struct{ A *map[string]string }{&map[string]string{"b": "c"}},
- }, {
- "a:",
- &struct{ A map[string]string }{},
- }, {
- "a: 1",
- &struct{ A int }{1},
- }, {
- "a: 1",
- &struct{ A float64 }{1},
- }, {
- "a: 1.0",
- &struct{ A int }{1},
- }, {
- "a: 1.0",
- &struct{ A uint }{1},
- }, {
- "a: [1, 2]",
- &struct{ A []int }{[]int{1, 2}},
- }, {
- "a: 1",
- &struct{ B int }{0},
- }, {
- "a: 1",
- &struct {
- B int "a"
- }{1},
- }, {
- "a: y",
- &struct{ A bool }{true},
- },
-
- // Some cross type conversions
- {
- "v: 42",
- map[string]uint{"v": 42},
- }, {
- "v: -42",
- map[string]uint{},
- }, {
- "v: 4294967296",
- map[string]uint64{"v": 4294967296},
- }, {
- "v: -4294967296",
- map[string]uint64{},
- },
-
- // int
- {
- "int_max: 2147483647",
- map[string]int{"int_max": math.MaxInt32},
- },
- {
- "int_min: -2147483648",
- map[string]int{"int_min": math.MinInt32},
- },
- {
- "int_overflow: 9223372036854775808", // math.MaxInt64 + 1
- map[string]int{},
- },
-
- // int64
- {
- "int64_max: 9223372036854775807",
- map[string]int64{"int64_max": math.MaxInt64},
- },
- {
- "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111",
- map[string]int64{"int64_max_base2": math.MaxInt64},
- },
- {
- "int64_min: -9223372036854775808",
- map[string]int64{"int64_min": math.MinInt64},
- },
- {
- "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111",
- map[string]int64{"int64_neg_base2": -math.MaxInt64},
- },
- {
- "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1
- map[string]int64{},
- },
-
- // uint
- {
- "uint_min: 0",
- map[string]uint{"uint_min": 0},
- },
- {
- "uint_max: 4294967295",
- map[string]uint{"uint_max": math.MaxUint32},
- },
- {
- "uint_underflow: -1",
- map[string]uint{},
- },
-
- // uint64
- {
- "uint64_min: 0",
- map[string]uint{"uint64_min": 0},
- },
- {
- "uint64_max: 18446744073709551615",
- map[string]uint64{"uint64_max": math.MaxUint64},
- },
- {
- "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111",
- map[string]uint64{"uint64_max_base2": math.MaxUint64},
- },
- {
- "uint64_maxint64: 9223372036854775807",
- map[string]uint64{"uint64_maxint64": math.MaxInt64},
- },
- {
- "uint64_underflow: -1",
- map[string]uint64{},
- },
-
- // float32
- {
- "float32_max: 3.40282346638528859811704183484516925440e+38",
- map[string]float32{"float32_max": math.MaxFloat32},
- },
- {
- "float32_nonzero: 1.401298464324817070923729583289916131280e-45",
- map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32},
- },
- {
- "float32_maxuint64: 18446744073709551615",
- map[string]float32{"float32_maxuint64": float32(math.MaxUint64)},
- },
- {
- "float32_maxuint64+1: 18446744073709551616",
- map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)},
- },
-
- // float64
- {
- "float64_max: 1.797693134862315708145274237317043567981e+308",
- map[string]float64{"float64_max": math.MaxFloat64},
- },
- {
- "float64_nonzero: 4.940656458412465441765687928682213723651e-324",
- map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64},
- },
- {
- "float64_maxuint64: 18446744073709551615",
- map[string]float64{"float64_maxuint64": float64(math.MaxUint64)},
- },
- {
- "float64_maxuint64+1: 18446744073709551616",
- map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)},
- },
-
- // Overflow cases.
- {
- "v: 4294967297",
- map[string]int32{},
- }, {
- "v: 128",
- map[string]int8{},
- },
-
- // Quoted values.
- {
- "'1': '\"2\"'",
- map[interface{}]interface{}{"1": "\"2\""},
- }, {
- "v:\n- A\n- 'B\n\n C'\n",
- map[string][]string{"v": []string{"A", "B\nC"}},
- },
-
- // Explicit tags.
- {
- "v: !!float '1.1'",
- map[string]interface{}{"v": 1.1},
- }, {
- "v: !!null ''",
- map[string]interface{}{"v": nil},
- }, {
- "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'",
- map[string]interface{}{"v": 1},
- },
-
- // Non-specific tag (Issue #75)
- {
- "v: ! test",
- map[string]interface{}{"v": "test"},
- },
-
- // Anchors and aliases.
- {
- "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
- &struct{ A, B, C, D int }{1, 2, 1, 2},
- }, {
- "a: &a {c: 1}\nb: *a",
- &struct {
- A, B struct {
- C int
- }
- }{struct{ C int }{1}, struct{ C int }{1}},
- }, {
- "a: &a [1, 2]\nb: *a",
- &struct{ B []int }{[]int{1, 2}},
- }, {
- "b: *a\na: &a {c: 1}",
- &struct {
- A, B struct {
- C int
- }
- }{struct{ C int }{1}, struct{ C int }{1}},
- },
-
- // Bug #1133337
- {
- "foo: ''",
- map[string]*string{"foo": new(string)},
- }, {
- "foo: null",
- map[string]*string{"foo": nil},
- }, {
- "foo: null",
- map[string]string{"foo": ""},
- }, {
- "foo: null",
- map[string]interface{}{"foo": nil},
- },
-
- // Support for ~
- {
- "foo: ~",
- map[string]*string{"foo": nil},
- }, {
- "foo: ~",
- map[string]string{"foo": ""},
- }, {
- "foo: ~",
- map[string]interface{}{"foo": nil},
- },
-
- // Ignored field
- {
- "a: 1\nb: 2\n",
- &struct {
- A int
- B int "-"
- }{1, 0},
- },
-
- // Bug #1191981
- {
- "" +
- "%YAML 1.1\n" +
- "--- !!str\n" +
- `"Generic line break (no glyph)\n\` + "\n" +
- ` Generic line break (glyphed)\n\` + "\n" +
- ` Line separator\u2028\` + "\n" +
- ` Paragraph separator\u2029"` + "\n",
- "" +
- "Generic line break (no glyph)\n" +
- "Generic line break (glyphed)\n" +
- "Line separator\u2028Paragraph separator\u2029",
- },
-
- // Struct inlining
- {
- "a: 1\nb: 2\nc: 3\n",
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- },
-
- // Map inlining
- {
- "a: 1\nb: 2\nc: 3\n",
- &struct {
- A int
- C map[string]int `yaml:",inline"`
- }{1, map[string]int{"b": 2, "c": 3}},
- },
-
- // bug 1243827
- {
- "a: -b_c",
- map[string]interface{}{"a": "-b_c"},
- },
- {
- "a: +b_c",
- map[string]interface{}{"a": "+b_c"},
- },
- {
- "a: 50cent_of_dollar",
- map[string]interface{}{"a": "50cent_of_dollar"},
- },
-
- // Duration
- {
- "a: 3s",
- map[string]time.Duration{"a": 3 * time.Second},
- },
-
- // Issue #24.
- {
- "a: <foo>",
- map[string]string{"a": "<foo>"},
- },
-
- // Base 60 floats are obsolete and unsupported.
- {
- "a: 1:1\n",
- map[string]string{"a": "1:1"},
- },
-
- // Binary data.
- {
- "a: !!binary gIGC\n",
- map[string]string{"a": "\x80\x81\x82"},
- }, {
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- map[string]string{"a": strings.Repeat("\x90", 54)},
- }, {
- "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
- map[string]string{"a": strings.Repeat("\x00", 52)},
- },
-
- // Ordered maps.
- {
- "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}",
- &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
- },
-
- // Issue #39.
- {
- "a:\n b:\n c: d\n",
- map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}},
- },
-
- // Custom map type.
- {
- "a: {b: c}",
- M{"a": M{"b": "c"}},
- },
-
- // Support encoding.TextUnmarshaler.
- {
- "a: 1.2.3.4\n",
- map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
- },
- {
- "a: 2015-02-24T18:19:39Z\n",
- map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)},
- },
-
- // Encode empty lists as zero-length slices.
- {
- "a: []",
- &struct{ A []int }{[]int{}},
- },
-
- // UTF-16-LE
- {
- "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00",
- M{"ñoño": "very yes"},
- },
- // UTF-16-LE with surrogate.
- {
- "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00",
- M{"ñoño": "very yes 🟔"},
- },
-
- // UTF-16-BE
- {
- "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n",
- M{"ñoño": "very yes"},
- },
- // UTF-16-BE with surrogate.
- {
- "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n",
- M{"ñoño": "very yes 🟔"},
- },
-
- // YAML Float regex shouldn't match this
- {
- "a: 123456e1\n",
- M{"a": "123456e1"},
- }, {
- "a: 123456E1\n",
- M{"a": "123456E1"},
- },
-}
-
-type M map[interface{}]interface{}
-
-type inlineB struct {
- B int
- inlineC `yaml:",inline"`
-}
-
-type inlineC struct {
- C int
-}
-
-func (s *S) TestUnmarshal(c *C) {
- for i, item := range unmarshalTests {
- c.Logf("test %d: %q", i, item.data)
- t := reflect.ValueOf(item.value).Type()
- var value interface{}
- switch t.Kind() {
- case reflect.Map:
- value = reflect.MakeMap(t).Interface()
- case reflect.String:
- value = reflect.New(t).Interface()
- case reflect.Ptr:
- value = reflect.New(t.Elem()).Interface()
- default:
- c.Fatalf("missing case for %s", t)
- }
- err := yaml.Unmarshal([]byte(item.data), value)
- if _, ok := err.(*yaml.TypeError); !ok {
- c.Assert(err, IsNil)
- }
- if t.Kind() == reflect.String {
- c.Assert(*value.(*string), Equals, item.value)
- } else {
- c.Assert(value, DeepEquals, item.value)
- }
- }
-}
-
-func (s *S) TestUnmarshalNaN(c *C) {
- value := map[string]interface{}{}
- err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
- c.Assert(err, IsNil)
- c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
-}
-
-var unmarshalErrorTests = []struct {
- data, error string
-}{
- {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
- {"v: [A,", "yaml: line 1: did not find expected node content"},
- {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
- {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
- {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
- {"value: -", "yaml: block sequence entries are not allowed in this context"},
- {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
- {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
- {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
- {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
-}
-
-func (s *S) TestUnmarshalErrors(c *C) {
- for _, item := range unmarshalErrorTests {
- var value interface{}
- err := yaml.Unmarshal([]byte(item.data), &value)
- c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
- }
-}
-
-var unmarshalerTests = []struct {
- data, tag string
- value interface{}
-}{
- {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}},
- {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
- {"_: 10", "!!int", 10},
- {"_: null", "!!null", nil},
- {`_: BAR!`, "!!str", "BAR!"},
- {`_: "BAR!"`, "!!str", "BAR!"},
- {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
- {`_: ""`, "!!str", ""},
-}
-
-var unmarshalerResult = map[int]error{}
-
-type unmarshalerType struct {
- value interface{}
-}
-
-func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
- if err := unmarshal(&o.value); err != nil {
- return err
- }
- if i, ok := o.value.(int); ok {
- if result, ok := unmarshalerResult[i]; ok {
- return result
- }
- }
- return nil
-}
-
-type unmarshalerPointer struct {
- Field *unmarshalerType "_"
-}
-
-type unmarshalerValue struct {
- Field unmarshalerType "_"
-}
-
-func (s *S) TestUnmarshalerPointerField(c *C) {
- for _, item := range unmarshalerTests {
- obj := &unmarshalerPointer{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- if item.value == nil {
- c.Assert(obj.Field, IsNil)
- } else {
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
- }
-}
-
-func (s *S) TestUnmarshalerValueField(c *C) {
- for _, item := range unmarshalerTests {
- obj := &unmarshalerValue{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
-}
-
-func (s *S) TestUnmarshalerWholeDocument(c *C) {
- obj := &unmarshalerType{}
- err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
- c.Assert(err, IsNil)
- value, ok := obj.value.(map[interface{}]interface{})
- c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
- c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
-}
-
-func (s *S) TestUnmarshalerTypeError(c *C) {
- unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
- unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
- defer func() {
- delete(unmarshalerResult, 2)
- delete(unmarshalerResult, 4)
- }()
-
- type T struct {
- Before int
- After int
- M map[string]*unmarshalerType
- }
- var v T
- data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
- err := yaml.Unmarshal([]byte(data), &v)
- c.Assert(err, ErrorMatches, ""+
- "yaml: unmarshal errors:\n"+
- " line 1: cannot unmarshal !!str `A` into int\n"+
- " foo\n"+
- " bar\n"+
- " line 1: cannot unmarshal !!str `B` into int")
- c.Assert(v.M["abc"], NotNil)
- c.Assert(v.M["def"], IsNil)
- c.Assert(v.M["ghi"], NotNil)
- c.Assert(v.M["jkl"], IsNil)
-
- c.Assert(v.M["abc"].value, Equals, 1)
- c.Assert(v.M["ghi"].value, Equals, 3)
-}
-
-type proxyTypeError struct{}
-
-func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
- var s string
- var a int32
- var b int64
- if err := unmarshal(&s); err != nil {
- panic(err)
- }
- if s == "a" {
- if err := unmarshal(&b); err == nil {
- panic("should have failed")
- }
- return unmarshal(&a)
- }
- if err := unmarshal(&a); err == nil {
- panic("should have failed")
- }
- return unmarshal(&b)
-}
-
-func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
- type T struct {
- Before int
- After int
- M map[string]*proxyTypeError
- }
- var v T
- data := `{before: A, m: {abc: a, def: b}, after: B}`
- err := yaml.Unmarshal([]byte(data), &v)
- c.Assert(err, ErrorMatches, ""+
- "yaml: unmarshal errors:\n"+
- " line 1: cannot unmarshal !!str `A` into int\n"+
- " line 1: cannot unmarshal !!str `a` into int32\n"+
- " line 1: cannot unmarshal !!str `b` into int64\n"+
- " line 1: cannot unmarshal !!str `B` into int")
-}
-
-type failingUnmarshaler struct{}
-
-var failingErr = errors.New("failingErr")
-
-func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
- return failingErr
-}
-
-func (s *S) TestUnmarshalerError(c *C) {
- err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
- c.Assert(err, Equals, failingErr)
-}
-
-type sliceUnmarshaler []int
-
-func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
- var slice []int
- err := unmarshal(&slice)
- if err == nil {
- *su = slice
- return nil
- }
-
- var intVal int
- err = unmarshal(&intVal)
- if err == nil {
- *su = []int{intVal}
- return nil
- }
-
- return err
-}
-
-func (s *S) TestUnmarshalerRetry(c *C) {
- var su sliceUnmarshaler
- err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
- c.Assert(err, IsNil)
- c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
-
- err = yaml.Unmarshal([]byte("1"), &su)
- c.Assert(err, IsNil)
- c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
-}
-
-// From http://yaml.org/type/merge.html
-var mergeTests = `
-anchors:
- list:
- - &CENTER { "x": 1, "y": 2 }
- - &LEFT { "x": 0, "y": 2 }
- - &BIG { "r": 10 }
- - &SMALL { "r": 1 }
-
-# All the following maps are equal:
-
-plain:
- # Explicit keys
- "x": 1
- "y": 2
- "r": 10
- label: center/big
-
-mergeOne:
- # Merge one map
- << : *CENTER
- "r": 10
- label: center/big
-
-mergeMultiple:
- # Merge multiple maps
- << : [ *CENTER, *BIG ]
- label: center/big
-
-override:
- # Override
- << : [ *BIG, *LEFT, *SMALL ]
- "x": 1
- label: center/big
-
-shortTag:
- # Explicit short merge tag
- !!merge "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-longTag:
- # Explicit merge long tag
- !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-inlineMap:
- # Inlined map
- << : {"x": 1, "y": 2, "r": 10}
- label: center/big
-
-inlineSequenceMap:
- # Inlined map in sequence
- << : [ *CENTER, {"r": 10} ]
- label: center/big
-`
-
-func (s *S) TestMerge(c *C) {
- var want = map[interface{}]interface{}{
- "x": 1,
- "y": 2,
- "r": 10,
- "label": "center/big",
- }
-
- var m map[interface{}]interface{}
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
- }
-}
-
-func (s *S) TestMergeStruct(c *C) {
- type Data struct {
- X, Y, R int
- Label string
- }
- want := Data{1, 2, 10, "center/big"}
-
- var m map[string]Data
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, Equals, want, Commentf("test %q failed", name))
- }
-}
-
-var unmarshalNullTests = []func() interface{}{
- func() interface{} { var v interface{}; v = "v"; return &v },
- func() interface{} { var s = "s"; return &s },
- func() interface{} { var s = "s"; sptr := &s; return &sptr },
- func() interface{} { var i = 1; return &i },
- func() interface{} { var i = 1; iptr := &i; return &iptr },
- func() interface{} { m := map[string]int{"s": 1}; return &m },
- func() interface{} { m := map[string]int{"s": 1}; return m },
-}
-
-func (s *S) TestUnmarshalNull(c *C) {
- for _, test := range unmarshalNullTests {
- item := test()
- zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
- err := yaml.Unmarshal([]byte("null"), item)
- c.Assert(err, IsNil)
- if reflect.TypeOf(item).Kind() == reflect.Map {
- c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
- } else {
- c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
- }
- }
-}
-
-func (s *S) TestUnmarshalSliceOnPreset(c *C) {
- // Issue #48.
- v := struct{ A []int }{[]int{1}}
- yaml.Unmarshal([]byte("a: [2]"), &v)
- c.Assert(v.A, DeepEquals, []int{2})
-}
-
-func (s *S) TestUnmarshalStrict(c *C) {
- v := struct{ A, B int }{}
-
- err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v)
- c.Check(err, IsNil)
- err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v)
- c.Check(err, IsNil)
- err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v)
- c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 3: field c not found in struct struct { A int; B int }")
-}
-
-//var data []byte
-//func init() {
-// var err error
-// data, err = ioutil.ReadFile("/tmp/file.yaml")
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkUnmarshal(c *C) {
-// var err error
-// for i := 0; i < c.N; i++ {
-// var v map[string]interface{}
-// err = yaml.Unmarshal(data, &v)
-// }
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkMarshal(c *C) {
-// var v map[string]interface{}
-// yaml.Unmarshal(data, &v)
-// c.ResetTimer()
-// for i := 0; i < c.N; i++ {
-// yaml.Marshal(&v)
-// }
-//}
diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go
index dcaf502f0..a1c2cc526 100644
--- a/vendor/gopkg.in/yaml.v2/emitterc.go
+++ b/vendor/gopkg.in/yaml.v2/emitterc.go
@@ -2,6 +2,7 @@ package yaml
import (
"bytes"
+ "fmt"
)
// Flush the buffer if needed.
@@ -664,7 +665,7 @@ func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t,
return yaml_emitter_emit_mapping_start(emitter, event)
default:
return yaml_emitter_set_emitter_error(emitter,
- "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS")
+ fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ))
}
}
@@ -842,7 +843,7 @@ func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event
return true
}
-// Write an achor.
+// Write an anchor.
func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool {
if emitter.anchor_data.anchor == nil {
return true
diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go
index 84f849955..a14435e82 100644
--- a/vendor/gopkg.in/yaml.v2/encode.go
+++ b/vendor/gopkg.in/yaml.v2/encode.go
@@ -3,12 +3,14 @@ package yaml
import (
"encoding"
"fmt"
+ "io"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
+ "unicode/utf8"
)
type encoder struct {
@@ -16,25 +18,39 @@ type encoder struct {
event yaml_event_t
out []byte
flow bool
+ // doneInit holds whether the initial stream_start_event has been
+ // emitted.
+ doneInit bool
}
-func newEncoder() (e *encoder) {
- e = &encoder{}
- e.must(yaml_emitter_initialize(&e.emitter))
+func newEncoder() *encoder {
+ e := &encoder{}
+ yaml_emitter_initialize(&e.emitter)
yaml_emitter_set_output_string(&e.emitter, &e.out)
yaml_emitter_set_unicode(&e.emitter, true)
- e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING))
- e.emit()
- e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true))
- e.emit()
return e
}
-func (e *encoder) finish() {
- e.must(yaml_document_end_event_initialize(&e.event, true))
+func newEncoderWithWriter(w io.Writer) *encoder {
+ e := &encoder{}
+ yaml_emitter_initialize(&e.emitter)
+ yaml_emitter_set_output_writer(&e.emitter, w)
+ yaml_emitter_set_unicode(&e.emitter, true)
+ return e
+}
+
+func (e *encoder) init() {
+ if e.doneInit {
+ return
+ }
+ yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)
e.emit()
+ e.doneInit = true
+}
+
+func (e *encoder) finish() {
e.emitter.open_ended = false
- e.must(yaml_stream_end_event_initialize(&e.event))
+ yaml_stream_end_event_initialize(&e.event)
e.emit()
}
@@ -44,9 +60,7 @@ func (e *encoder) destroy() {
func (e *encoder) emit() {
// This will internally delete the e.event value.
- if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT {
- e.must(false)
- }
+ e.must(yaml_emitter_emit(&e.emitter, &e.event))
}
func (e *encoder) must(ok bool) {
@@ -59,13 +73,28 @@ func (e *encoder) must(ok bool) {
}
}
+func (e *encoder) marshalDoc(tag string, in reflect.Value) {
+ e.init()
+ yaml_document_start_event_initialize(&e.event, nil, nil, true)
+ e.emit()
+ e.marshal(tag, in)
+ yaml_document_end_event_initialize(&e.event, true)
+ e.emit()
+}
+
func (e *encoder) marshal(tag string, in reflect.Value) {
- if !in.IsValid() {
+ if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() {
e.nilv()
return
}
iface := in.Interface()
- if m, ok := iface.(Marshaler); ok {
+ switch m := iface.(type) {
+ case time.Time, *time.Time:
+ // Although time.Time implements TextMarshaler,
+ // we don't want to treat it as a string for YAML
+ // purposes because YAML has special support for
+ // timestamps.
+ case Marshaler:
v, err := m.MarshalYAML()
if err != nil {
fail(err)
@@ -75,31 +104,34 @@ func (e *encoder) marshal(tag string, in reflect.Value) {
return
}
in = reflect.ValueOf(v)
- } else if m, ok := iface.(encoding.TextMarshaler); ok {
+ case encoding.TextMarshaler:
text, err := m.MarshalText()
if err != nil {
fail(err)
}
in = reflect.ValueOf(string(text))
+ case nil:
+ e.nilv()
+ return
}
switch in.Kind() {
case reflect.Interface:
- if in.IsNil() {
- e.nilv()
- } else {
- e.marshal(tag, in.Elem())
- }
+ e.marshal(tag, in.Elem())
case reflect.Map:
e.mapv(tag, in)
case reflect.Ptr:
- if in.IsNil() {
- e.nilv()
+ if in.Type() == ptrTimeType {
+ e.timev(tag, in.Elem())
} else {
e.marshal(tag, in.Elem())
}
case reflect.Struct:
- e.structv(tag, in)
- case reflect.Slice:
+ if in.Type() == timeType {
+ e.timev(tag, in)
+ } else {
+ e.structv(tag, in)
+ }
+ case reflect.Slice, reflect.Array:
if in.Type().Elem() == mapItemType {
e.itemsv(tag, in)
} else {
@@ -191,10 +223,10 @@ func (e *encoder) mappingv(tag string, f func()) {
e.flow = false
style = yaml_FLOW_MAPPING_STYLE
}
- e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
+ yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)
e.emit()
f()
- e.must(yaml_mapping_end_event_initialize(&e.event))
+ yaml_mapping_end_event_initialize(&e.event)
e.emit()
}
@@ -240,23 +272,36 @@ var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0
func (e *encoder) stringv(tag string, in reflect.Value) {
var style yaml_scalar_style_t
s := in.String()
- rtag, rs := resolve("", s)
- if rtag == yaml_BINARY_TAG {
- if tag == "" || tag == yaml_STR_TAG {
- tag = rtag
- s = rs.(string)
- } else if tag == yaml_BINARY_TAG {
+ canUsePlain := true
+ switch {
+ case !utf8.ValidString(s):
+ if tag == yaml_BINARY_TAG {
failf("explicitly tagged !!binary data must be base64-encoded")
- } else {
+ }
+ if tag != "" {
failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
}
+ // It can't be encoded directly as YAML so use a binary tag
+ // and encode it as base64.
+ tag = yaml_BINARY_TAG
+ s = encodeBase64(s)
+ case tag == "":
+ // Check to see if it would resolve to a specific
+ // tag when encoded unquoted. If it doesn't,
+ // there's no need to quote it.
+ rtag, _ := resolve("", s)
+ canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s)
}
- if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) {
- style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
- } else if strings.Contains(s, "\n") {
+ // Note: it's possible for user code to emit invalid YAML
+ // if they explicitly specify a tag and a string containing
+ // text that's incompatible with that tag.
+ switch {
+ case strings.Contains(s, "\n"):
style = yaml_LITERAL_SCALAR_STYLE
- } else {
+ case canUsePlain:
style = yaml_PLAIN_SCALAR_STYLE
+ default:
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
e.emitScalar(s, "", tag, style)
}
@@ -281,9 +326,20 @@ func (e *encoder) uintv(tag string, in reflect.Value) {
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
+func (e *encoder) timev(tag string, in reflect.Value) {
+ t := in.Interface().(time.Time)
+ s := t.Format(time.RFC3339Nano)
+ e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
+}
+
func (e *encoder) floatv(tag string, in reflect.Value) {
- // FIXME: Handle 64 bits here.
- s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32)
+ // Issue #352: When formatting, use the precision of the underlying value
+ precision := 64
+ if in.Kind() == reflect.Float32 {
+ precision = 32
+ }
+
+ s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
switch s {
case "+Inf":
s = ".inf"
diff --git a/vendor/gopkg.in/yaml.v2/encode_test.go b/vendor/gopkg.in/yaml.v2/encode_test.go
deleted file mode 100644
index 84099bd38..000000000
--- a/vendor/gopkg.in/yaml.v2/encode_test.go
+++ /dev/null
@@ -1,501 +0,0 @@
-package yaml_test
-
-import (
- "fmt"
- "math"
- "strconv"
- "strings"
- "time"
-
- . "gopkg.in/check.v1"
- "gopkg.in/yaml.v2"
- "net"
- "os"
-)
-
-var marshalIntTest = 123
-
-var marshalTests = []struct {
- value interface{}
- data string
-}{
- {
- nil,
- "null\n",
- }, {
- &struct{}{},
- "{}\n",
- }, {
- map[string]string{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]interface{}{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]string{"v": "true"},
- "v: \"true\"\n",
- }, {
- map[string]string{"v": "false"},
- "v: \"false\"\n",
- }, {
- map[string]interface{}{"v": true},
- "v: true\n",
- }, {
- map[string]interface{}{"v": false},
- "v: false\n",
- }, {
- map[string]interface{}{"v": 10},
- "v: 10\n",
- }, {
- map[string]interface{}{"v": -10},
- "v: -10\n",
- }, {
- map[string]uint{"v": 42},
- "v: 42\n",
- }, {
- map[string]interface{}{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]int64{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]uint64{"v": 4294967296},
- "v: 4294967296\n",
- }, {
- map[string]interface{}{"v": "10"},
- "v: \"10\"\n",
- }, {
- map[string]interface{}{"v": 0.1},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": float64(0.1)},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": -0.1},
- "v: -0.1\n",
- }, {
- map[string]interface{}{"v": math.Inf(+1)},
- "v: .inf\n",
- }, {
- map[string]interface{}{"v": math.Inf(-1)},
- "v: -.inf\n",
- }, {
- map[string]interface{}{"v": math.NaN()},
- "v: .nan\n",
- }, {
- map[string]interface{}{"v": nil},
- "v: null\n",
- }, {
- map[string]interface{}{"v": ""},
- "v: \"\"\n",
- }, {
- map[string][]string{"v": []string{"A", "B"}},
- "v:\n- A\n- B\n",
- }, {
- map[string][]string{"v": []string{"A", "B\nC"}},
- "v:\n- A\n- |-\n B\n C\n",
- }, {
- map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}},
- "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
- }, {
- map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- "a:\n b: c\n",
- }, {
- map[string]interface{}{"a": "-"},
- "a: '-'\n",
- },
-
- // Simple values.
- {
- &marshalIntTest,
- "123\n",
- },
-
- // Structures
- {
- &struct{ Hello string }{"world"},
- "hello: world\n",
- }, {
- &struct {
- A struct {
- B string
- }
- }{struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{&struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{},
- "a: null\n",
- }, {
- &struct{ A int }{1},
- "a: 1\n",
- }, {
- &struct{ A []int }{[]int{1, 2}},
- "a:\n- 1\n- 2\n",
- }, {
- &struct {
- B int "a"
- }{1},
- "a: 1\n",
- }, {
- &struct{ A bool }{true},
- "a: true\n",
- },
-
- // Conditional flag
- {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{1, 0},
- "a: 1\n",
- }, {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{0, 0},
- "{}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{&struct{ X, y int }{1, 2}},
- "a: {x: 1}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{nil},
- "{}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{&struct{ X, y int }{}},
- "a: {x: 0}\n",
- }, {
- &struct {
- A struct{ X, y int } "a,omitempty,flow"
- }{struct{ X, y int }{1, 2}},
- "a: {x: 1}\n",
- }, {
- &struct {
- A struct{ X, y int } "a,omitempty,flow"
- }{struct{ X, y int }{0, 1}},
- "{}\n",
- }, {
- &struct {
- A float64 "a,omitempty"
- B float64 "b,omitempty"
- }{1, 0},
- "a: 1\n",
- },
-
- // Flow flag
- {
- &struct {
- A []int "a,flow"
- }{[]int{1, 2}},
- "a: [1, 2]\n",
- }, {
- &struct {
- A map[string]string "a,flow"
- }{map[string]string{"b": "c", "d": "e"}},
- "a: {b: c, d: e}\n",
- }, {
- &struct {
- A struct {
- B, D string
- } "a,flow"
- }{struct{ B, D string }{"c", "e"}},
- "a: {b: c, d: e}\n",
- },
-
- // Unexported field
- {
- &struct {
- u int
- A int
- }{0, 1},
- "a: 1\n",
- },
-
- // Ignored field
- {
- &struct {
- A int
- B int "-"
- }{1, 2},
- "a: 1\n",
- },
-
- // Struct inlining
- {
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- "a: 1\nb: 2\nc: 3\n",
- },
-
- // Map inlining
- {
- &struct {
- A int
- C map[string]int `yaml:",inline"`
- }{1, map[string]int{"b": 2, "c": 3}},
- "a: 1\nb: 2\nc: 3\n",
- },
-
- // Duration
- {
- map[string]time.Duration{"a": 3 * time.Second},
- "a: 3s\n",
- },
-
- // Issue #24: bug in map merging logic.
- {
- map[string]string{"a": "<foo>"},
- "a: <foo>\n",
- },
-
- // Issue #34: marshal unsupported base 60 floats quoted for compatibility
- // with old YAML 1.1 parsers.
- {
- map[string]string{"a": "1:1"},
- "a: \"1:1\"\n",
- },
-
- // Binary data.
- {
- map[string]string{"a": "\x00"},
- "a: \"\\0\"\n",
- }, {
- map[string]string{"a": "\x80\x81\x82"},
- "a: !!binary gIGC\n",
- }, {
- map[string]string{"a": strings.Repeat("\x90", 54)},
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- },
-
- // Ordered maps.
- {
- &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
- "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n",
- },
-
- // Encode unicode as utf-8 rather than in escaped form.
- {
- map[string]string{"a": "你好"},
- "a: 你好\n",
- },
-
- // Support encoding.TextMarshaler.
- {
- map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
- "a: 1.2.3.4\n",
- },
- {
- map[string]time.Time{"a": time.Unix(1424801979, 0)},
- "a: 2015-02-24T18:19:39Z\n",
- },
-
- // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible).
- {
- map[string]string{"a": "b: c"},
- "a: 'b: c'\n",
- },
-
- // Containing hash mark ('#') in string should be quoted
- {
- map[string]string{"a": "Hello #comment"},
- "a: 'Hello #comment'\n",
- },
- {
- map[string]string{"a": "你好 #comment"},
- "a: '你好 #comment'\n",
- },
-}
-
-func (s *S) TestMarshal(c *C) {
- defer os.Setenv("TZ", os.Getenv("TZ"))
- os.Setenv("TZ", "UTC")
- for _, item := range marshalTests {
- data, err := yaml.Marshal(item.value)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, item.data)
- }
-}
-
-var marshalErrorTests = []struct {
- value interface{}
- error string
- panic string
-}{{
- value: &struct {
- B int
- inlineB ",inline"
- }{1, inlineB{2, inlineC{3}}},
- panic: `Duplicated key 'b' in struct struct \{ B int; .*`,
-}, {
- value: &struct {
- A int
- B map[string]int ",inline"
- }{1, map[string]int{"a": 2}},
- panic: `Can't have key "a" in inlined map; conflicts with struct field`,
-}}
-
-func (s *S) TestMarshalErrors(c *C) {
- for _, item := range marshalErrorTests {
- if item.panic != "" {
- c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic)
- } else {
- _, err := yaml.Marshal(item.value)
- c.Assert(err, ErrorMatches, item.error)
- }
- }
-}
-
-func (s *S) TestMarshalTypeCache(c *C) {
- var data []byte
- var err error
- func() {
- type T struct{ A int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- func() {
- type T struct{ B int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- c.Assert(string(data), Equals, "b: 0\n")
-}
-
-var marshalerTests = []struct {
- data string
- value interface{}
-}{
- {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}},
- {"_:\n- 1\n- A\n", []interface{}{1, "A"}},
- {"_: 10\n", 10},
- {"_: null\n", nil},
- {"_: BAR!\n", "BAR!"},
-}
-
-type marshalerType struct {
- value interface{}
-}
-
-func (o marshalerType) MarshalText() ([]byte, error) {
- panic("MarshalText called on type with MarshalYAML")
-}
-
-func (o marshalerType) MarshalYAML() (interface{}, error) {
- return o.value, nil
-}
-
-type marshalerValue struct {
- Field marshalerType "_"
-}
-
-func (s *S) TestMarshaler(c *C) {
- for _, item := range marshalerTests {
- obj := &marshalerValue{}
- obj.Field.value = item.value
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, string(item.data))
- }
-}
-
-func (s *S) TestMarshalerWholeDocument(c *C) {
- obj := &marshalerType{}
- obj.value = map[string]string{"hello": "world!"}
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, "hello: world!\n")
-}
-
-type failingMarshaler struct{}
-
-func (ft *failingMarshaler) MarshalYAML() (interface{}, error) {
- return nil, failingErr
-}
-
-func (s *S) TestMarshalerError(c *C) {
- _, err := yaml.Marshal(&failingMarshaler{})
- c.Assert(err, Equals, failingErr)
-}
-
-func (s *S) TestSortedOutput(c *C) {
- order := []interface{}{
- false,
- true,
- 1,
- uint(1),
- 1.0,
- 1.1,
- 1.2,
- 2,
- uint(2),
- 2.0,
- 2.1,
- "",
- ".1",
- ".2",
- ".a",
- "1",
- "2",
- "a!10",
- "a/2",
- "a/10",
- "a~10",
- "ab/1",
- "b/1",
- "b/01",
- "b/2",
- "b/02",
- "b/3",
- "b/03",
- "b1",
- "b01",
- "b3",
- "c2.10",
- "c10.2",
- "d1",
- "d12",
- "d12a",
- }
- m := make(map[interface{}]int)
- for _, k := range order {
- m[k] = 1
- }
- data, err := yaml.Marshal(m)
- c.Assert(err, IsNil)
- out := "\n" + string(data)
- last := 0
- for i, k := range order {
- repr := fmt.Sprint(k)
- if s, ok := k.(string); ok {
- if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
- repr = `"` + repr + `"`
- }
- }
- index := strings.Index(out, "\n"+repr+":")
- if index == -1 {
- c.Fatalf("%#v is not in the output: %#v", k, out)
- }
- if index < last {
- c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
- }
- last = index
- }
-}
diff --git a/vendor/gopkg.in/yaml.v2/example_embedded_test.go b/vendor/gopkg.in/yaml.v2/example_embedded_test.go
deleted file mode 100644
index 171c0931a..000000000
--- a/vendor/gopkg.in/yaml.v2/example_embedded_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package yaml_test
-
-import (
- "fmt"
- "log"
-
- "gopkg.in/yaml.v2"
-)
-
-// An example showing how to unmarshal embedded
-// structs from YAML.
-
-type StructA struct {
- A string `yaml:"a"`
-}
-
-type StructB struct {
- // Embedded structs are not treated as embedded in YAML by default. To do that,
- // add the ",inline" annotation below
- StructA `yaml:",inline"`
- B string `yaml:"b"`
-}
-
-var data = `
-a: a string from struct A
-b: a string from struct B
-`
-
-func ExampleUnmarshal_embedded() {
- var b StructB
-
- err := yaml.Unmarshal([]byte(data), &b)
- if err != nil {
- log.Fatalf("cannot unmarshal data: %v", err)
- }
- fmt.Println(b.A)
- fmt.Println(b.B)
- // Output:
- // a string from struct A
- // a string from struct B
-}
diff --git a/vendor/gopkg.in/yaml.v2/go.mod b/vendor/gopkg.in/yaml.v2/go.mod
new file mode 100644
index 000000000..1934e8769
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/go.mod
@@ -0,0 +1,5 @@
+module "gopkg.in/yaml.v2"
+
+require (
+ "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405
+)
diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go
index f45079171..7c1f5fac3 100644
--- a/vendor/gopkg.in/yaml.v2/readerc.go
+++ b/vendor/gopkg.in/yaml.v2/readerc.go
@@ -93,9 +93,18 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
panic("read handler must be set")
}
+ // [Go] This function was changed to guarantee the requested length size at EOF.
+ // The fact we need to do this is pretty awful, but the description above implies
+ // for that to be the case, and there are tests
+
// If the EOF flag is set and the raw buffer is empty, do nothing.
if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) {
- return true
+ // [Go] ACTUALLY! Read the documentation of this function above.
+ // This is just broken. To return true, we need to have the
+ // given length in the buffer. Not doing that means every single
+ // check that calls this function to make sure the buffer has a
+ // given length is Go) panicking; or C) accessing invalid memory.
+ //return true
}
// Return if the buffer contains enough characters.
@@ -389,6 +398,15 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
break
}
}
+ // [Go] Read the documentation of this function above. To return true,
+ // we need to have the given length in the buffer. Not doing that means
+ // every single check that calls this function to make sure the buffer
+ // has a given length is Go) panicking; or C) accessing invalid memory.
+ // This happens here due to the EOF above breaking early.
+ for buffer_len < length {
+ parser.buffer[buffer_len] = 0
+ buffer_len++
+ }
parser.buffer = parser.buffer[:buffer_len]
return true
}
diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go
index 232313cc0..6c151db6f 100644
--- a/vendor/gopkg.in/yaml.v2/resolve.go
+++ b/vendor/gopkg.in/yaml.v2/resolve.go
@@ -6,7 +6,7 @@ import (
"regexp"
"strconv"
"strings"
- "unicode/utf8"
+ "time"
)
type resolveMapItem struct {
@@ -75,7 +75,7 @@ func longTag(tag string) string {
func resolvableTag(tag string) bool {
switch tag {
- case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG:
+ case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG:
return true
}
return false
@@ -92,6 +92,19 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
switch tag {
case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG:
return
+ case yaml_FLOAT_TAG:
+ if rtag == yaml_INT_TAG {
+ switch v := out.(type) {
+ case int64:
+ rtag = yaml_FLOAT_TAG
+ out = float64(v)
+ return
+ case int:
+ rtag = yaml_FLOAT_TAG
+ out = float64(v)
+ return
+ }
+ }
}
failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))
}()
@@ -125,6 +138,15 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
case 'D', 'S':
// Int, float, or timestamp.
+ // Only try values as a timestamp if the value is unquoted or there's an explicit
+ // !!timestamp tag.
+ if tag == "" || tag == yaml_TIMESTAMP_TAG {
+ t, ok := parseTimestamp(in)
+ if ok {
+ return yaml_TIMESTAMP_TAG, t
+ }
+ }
+
plain := strings.Replace(in, "_", "", -1)
intv, err := strconv.ParseInt(plain, 0, 64)
if err == nil {
@@ -158,28 +180,20 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
return yaml_INT_TAG, uintv
}
} else if strings.HasPrefix(plain, "-0b") {
- intv, err := strconv.ParseInt(plain[3:], 2, 64)
+ intv, err := strconv.ParseInt("-" + plain[3:], 2, 64)
if err == nil {
- if intv == int64(int(intv)) {
- return yaml_INT_TAG, -int(intv)
+ if true || intv == int64(int(intv)) {
+ return yaml_INT_TAG, int(intv)
} else {
- return yaml_INT_TAG, -intv
+ return yaml_INT_TAG, intv
}
}
}
- // XXX Handle timestamps here.
-
default:
panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")")
}
}
- if tag == yaml_BINARY_TAG {
- return yaml_BINARY_TAG, in
- }
- if utf8.ValidString(in) {
- return yaml_STR_TAG, in
- }
- return yaml_BINARY_TAG, encodeBase64(in)
+ return yaml_STR_TAG, in
}
// encodeBase64 encodes s as base64 that is broken up into multiple lines
@@ -206,3 +220,39 @@ func encodeBase64(s string) string {
}
return string(out[:k])
}
+
+// This is a subset of the formats allowed by the regular expression
+// defined at http://yaml.org/type/timestamp.html.
+var allowedTimestampFormats = []string{
+ "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields.
+ "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t".
+ "2006-1-2 15:4:5.999999999", // space separated with no time zone
+ "2006-1-2", // date only
+ // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5"
+ // from the set of examples.
+}
+
+// parseTimestamp parses s as a timestamp string and
+// returns the timestamp and reports whether it succeeded.
+// Timestamp formats are defined at http://yaml.org/type/timestamp.html
+func parseTimestamp(s string) (time.Time, bool) {
+ // TODO write code to check all the formats supported by
+ // http://yaml.org/type/timestamp.html instead of using time.Parse.
+
+ // Quick check: all date formats start with YYYY-.
+ i := 0
+ for ; i < len(s); i++ {
+ if c := s[i]; c < '0' || c > '9' {
+ break
+ }
+ }
+ if i != 4 || i == len(s) || s[i] != '-' {
+ return time.Time{}, false
+ }
+ for _, format := range allowedTimestampFormats {
+ if t, err := time.Parse(format, s); err == nil {
+ return t, true
+ }
+ }
+ return time.Time{}, false
+}
diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go
index 074484455..077fd1dd2 100644
--- a/vendor/gopkg.in/yaml.v2/scannerc.go
+++ b/vendor/gopkg.in/yaml.v2/scannerc.go
@@ -871,12 +871,6 @@ func yaml_parser_save_simple_key(parser *yaml_parser_t) bool {
required := parser.flow_level == 0 && parser.indent == parser.mark.column
- // A simple key is required only when it is the first token in the current
- // line. Therefore it is always allowed. But we add a check anyway.
- if required && !parser.simple_key_allowed {
- panic("should not happen")
- }
-
//
// If the current position may start a simple key, save it.
//
@@ -2475,6 +2469,10 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si
}
}
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
// Check if we are at the end of the scalar.
if single {
if parser.buffer[parser.buffer_pos] == '\'' {
@@ -2487,10 +2485,6 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si
}
// Consume blank characters.
- if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
- return false
- }
-
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) {
// Consume a space or a tab character.
@@ -2592,19 +2586,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b
// Consume non-blank characters.
for !is_blankz(parser.buffer, parser.buffer_pos) {
- // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13".
- if parser.flow_level > 0 &&
- parser.buffer[parser.buffer_pos] == ':' &&
- !is_blankz(parser.buffer, parser.buffer_pos+1) {
- yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
- start_mark, "found unexpected ':'")
- return false
- }
-
// Check for indicators that may end a plain scalar.
if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) ||
(parser.flow_level > 0 &&
- (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' ||
+ (parser.buffer[parser.buffer_pos] == ',' ||
parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' ||
parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
parser.buffer[parser.buffer_pos] == '}')) {
@@ -2656,10 +2641,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) {
- // Check for tab character that abuse indentation.
+ // Check for tab characters that abuse indentation.
if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
- start_mark, "found a tab character that violate indentation")
+ start_mark, "found a tab character that violates indentation")
return false
}
diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go
index 5958822f9..4c45e660a 100644
--- a/vendor/gopkg.in/yaml.v2/sorter.go
+++ b/vendor/gopkg.in/yaml.v2/sorter.go
@@ -51,6 +51,15 @@ func (l keyList) Less(i, j int) bool {
}
var ai, bi int
var an, bn int64
+ if ar[i] == '0' || br[i] == '0' {
+ for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- {
+ if ar[j] != '0' {
+ an = 1
+ bn = 1
+ break
+ }
+ }
+ }
for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
an = an*10 + int64(ar[ai]-'0')
}
diff --git a/vendor/gopkg.in/yaml.v2/suite_test.go b/vendor/gopkg.in/yaml.v2/suite_test.go
deleted file mode 100644
index c5cf1ed4f..000000000
--- a/vendor/gopkg.in/yaml.v2/suite_test.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package yaml_test
-
-import (
- . "gopkg.in/check.v1"
- "testing"
-)
-
-func Test(t *testing.T) { TestingT(t) }
-
-type S struct{}
-
-var _ = Suite(&S{})
diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go
index 190362f25..a2dde608c 100644
--- a/vendor/gopkg.in/yaml.v2/writerc.go
+++ b/vendor/gopkg.in/yaml.v2/writerc.go
@@ -18,72 +18,9 @@ func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
return true
}
- // If the output encoding is UTF-8, we don't need to recode the buffer.
- if emitter.encoding == yaml_UTF8_ENCODING {
- if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
- return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
- }
- emitter.buffer_pos = 0
- return true
- }
-
- // Recode the buffer into the raw buffer.
- var low, high int
- if emitter.encoding == yaml_UTF16LE_ENCODING {
- low, high = 0, 1
- } else {
- high, low = 1, 0
- }
-
- pos := 0
- for pos < emitter.buffer_pos {
- // See the "reader.c" code for more details on UTF-8 encoding. Note
- // that we assume that the buffer contains a valid UTF-8 sequence.
-
- // Read the next UTF-8 character.
- octet := emitter.buffer[pos]
-
- var w int
- var value rune
- switch {
- case octet&0x80 == 0x00:
- w, value = 1, rune(octet&0x7F)
- case octet&0xE0 == 0xC0:
- w, value = 2, rune(octet&0x1F)
- case octet&0xF0 == 0xE0:
- w, value = 3, rune(octet&0x0F)
- case octet&0xF8 == 0xF0:
- w, value = 4, rune(octet&0x07)
- }
- for k := 1; k < w; k++ {
- octet = emitter.buffer[pos+k]
- value = (value << 6) + (rune(octet) & 0x3F)
- }
- pos += w
-
- // Write the character.
- if value < 0x10000 {
- var b [2]byte
- b[high] = byte(value >> 8)
- b[low] = byte(value & 0xFF)
- emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1])
- } else {
- // Write the character using a surrogate pair (check "reader.c").
- var b [4]byte
- value -= 0x10000
- b[high] = byte(0xD8 + (value >> 18))
- b[low] = byte((value >> 10) & 0xFF)
- b[high+2] = byte(0xDC + ((value >> 8) & 0xFF))
- b[low+2] = byte(value & 0xFF)
- emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3])
- }
- }
-
- // Write the raw buffer.
- if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil {
+ if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
}
emitter.buffer_pos = 0
- emitter.raw_buffer = emitter.raw_buffer[:0]
return true
}
diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go
index 5e3c2daee..de85aa4cd 100644
--- a/vendor/gopkg.in/yaml.v2/yaml.go
+++ b/vendor/gopkg.in/yaml.v2/yaml.go
@@ -9,6 +9,7 @@ package yaml
import (
"errors"
"fmt"
+ "io"
"reflect"
"strings"
"sync"
@@ -81,12 +82,58 @@ func Unmarshal(in []byte, out interface{}) (err error) {
}
// UnmarshalStrict is like Unmarshal except that any fields that are found
-// in the data that do not have corresponding struct members will result in
+// in the data that do not have corresponding struct members, or mapping
+// keys that are duplicates, will result in
// an error.
func UnmarshalStrict(in []byte, out interface{}) (err error) {
return unmarshal(in, out, true)
}
+// A Decorder reads and decodes YAML values from an input stream.
+type Decoder struct {
+ strict bool
+ parser *parser
+}
+
+// NewDecoder returns a new decoder that reads from r.
+//
+// The decoder introduces its own buffering and may read
+// data from r beyond the YAML values requested.
+func NewDecoder(r io.Reader) *Decoder {
+ return &Decoder{
+ parser: newParserFromReader(r),
+ }
+}
+
+// SetStrict sets whether strict decoding behaviour is enabled when
+// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict.
+func (dec *Decoder) SetStrict(strict bool) {
+ dec.strict = strict
+}
+
+// Decode reads the next YAML-encoded value from its input
+// and stores it in the value pointed to by v.
+//
+// See the documentation for Unmarshal for details about the
+// conversion of YAML into a Go value.
+func (dec *Decoder) Decode(v interface{}) (err error) {
+ d := newDecoder(dec.strict)
+ defer handleErr(&err)
+ node := dec.parser.parse()
+ if node == nil {
+ return io.EOF
+ }
+ out := reflect.ValueOf(v)
+ if out.Kind() == reflect.Ptr && !out.IsNil() {
+ out = out.Elem()
+ }
+ d.unmarshal(node, out)
+ if len(d.terrors) > 0 {
+ return &TypeError{d.terrors}
+ }
+ return nil
+}
+
func unmarshal(in []byte, out interface{}, strict bool) (err error) {
defer handleErr(&err)
d := newDecoder(strict)
@@ -110,8 +157,8 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) {
// of the generated document will reflect the structure of the value itself.
// Maps and pointers (to struct, string, int, etc) are accepted as the in value.
//
-// Struct fields are only unmarshalled if they are exported (have an upper case
-// first letter), and are unmarshalled using the field name lowercased as the
+// Struct fields are only marshalled if they are exported (have an upper case
+// first letter), and are marshalled using the field name lowercased as the
// default key. Custom keys may be defined via the "yaml" name in the field
// tag: the content preceding the first comma is used as the key, and the
// following comma-separated options are used to tweak the marshalling process.
@@ -125,7 +172,10 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) {
//
// omitempty Only include the field if it's not set to the zero
// value for the type or to empty slices or maps.
-// Does not apply to zero valued structs.
+// Zero valued structs will be omitted if all their public
+// fields are zero, unless they implement an IsZero
+// method (see the IsZeroer interface type), in which
+// case the field will be included if that method returns true.
//
// flow Marshal using a flow style (useful for structs,
// sequences and maps).
@@ -150,12 +200,47 @@ func Marshal(in interface{}) (out []byte, err error) {
defer handleErr(&err)
e := newEncoder()
defer e.destroy()
- e.marshal("", reflect.ValueOf(in))
+ e.marshalDoc("", reflect.ValueOf(in))
e.finish()
out = e.out
return
}
+// An Encoder writes YAML values to an output stream.
+type Encoder struct {
+ encoder *encoder
+}
+
+// NewEncoder returns a new encoder that writes to w.
+// The Encoder should be closed after use to flush all data
+// to w.
+func NewEncoder(w io.Writer) *Encoder {
+ return &Encoder{
+ encoder: newEncoderWithWriter(w),
+ }
+}
+
+// Encode writes the YAML encoding of v to the stream.
+// If multiple items are encoded to the stream, the
+// second and subsequent document will be preceded
+// with a "---" document separator, but the first will not.
+//
+// See the documentation for Marshal for details about the conversion of Go
+// values to YAML.
+func (e *Encoder) Encode(v interface{}) (err error) {
+ defer handleErr(&err)
+ e.encoder.marshalDoc("", reflect.ValueOf(v))
+ return nil
+}
+
+// Close closes the encoder by writing any remaining data.
+// It does not write a stream terminating string "...".
+func (e *Encoder) Close() (err error) {
+ defer handleErr(&err)
+ e.encoder.finish()
+ return nil
+}
+
func handleErr(err *error) {
if v := recover(); v != nil {
if e, ok := v.(yamlError); ok {
@@ -211,6 +296,9 @@ type fieldInfo struct {
Num int
OmitEmpty bool
Flow bool
+ // Id holds the unique field identifier, so we can cheaply
+ // check for field duplicates without maintaining an extra map.
+ Id int
// Inline holds the field index if the field is part of an inlined struct.
Inline []int
@@ -290,6 +378,7 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
} else {
finfo.Inline = append([]int{i}, finfo.Inline...)
}
+ finfo.Id = len(fieldsList)
fieldsMap[finfo.Key] = finfo
fieldsList = append(fieldsList, finfo)
}
@@ -311,11 +400,16 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
return nil, errors.New(msg)
}
+ info.Id = len(fieldsList)
fieldsList = append(fieldsList, info)
fieldsMap[info.Key] = info
}
- sinfo = &structInfo{fieldsMap, fieldsList, inlineMap}
+ sinfo = &structInfo{
+ FieldsMap: fieldsMap,
+ FieldsList: fieldsList,
+ InlineMap: inlineMap,
+ }
fieldMapMutex.Lock()
structMap[st] = sinfo
@@ -323,8 +417,23 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
return sinfo, nil
}
+// IsZeroer is used to check whether an object is zero to
+// determine whether it should be omitted when marshaling
+// with the omitempty flag. One notable implementation
+// is time.Time.
+type IsZeroer interface {
+ IsZero() bool
+}
+
func isZero(v reflect.Value) bool {
- switch v.Kind() {
+ kind := v.Kind()
+ if z, ok := v.Interface().(IsZeroer); ok {
+ if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {
+ return true
+ }
+ return z.IsZero()
+ }
+ switch kind {
case reflect.String:
return len(v.String()) == 0
case reflect.Interface, reflect.Ptr:
diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go
index 3caeca049..e25cee563 100644
--- a/vendor/gopkg.in/yaml.v2/yamlh.go
+++ b/vendor/gopkg.in/yaml.v2/yamlh.go
@@ -1,6 +1,7 @@
package yaml
import (
+ "fmt"
"io"
)
@@ -239,6 +240,27 @@ const (
yaml_MAPPING_END_EVENT // A MAPPING-END event.
)
+var eventStrings = []string{
+ yaml_NO_EVENT: "none",
+ yaml_STREAM_START_EVENT: "stream start",
+ yaml_STREAM_END_EVENT: "stream end",
+ yaml_DOCUMENT_START_EVENT: "document start",
+ yaml_DOCUMENT_END_EVENT: "document end",
+ yaml_ALIAS_EVENT: "alias",
+ yaml_SCALAR_EVENT: "scalar",
+ yaml_SEQUENCE_START_EVENT: "sequence start",
+ yaml_SEQUENCE_END_EVENT: "sequence end",
+ yaml_MAPPING_START_EVENT: "mapping start",
+ yaml_MAPPING_END_EVENT: "mapping end",
+}
+
+func (e yaml_event_type_t) String() string {
+ if e < 0 || int(e) >= len(eventStrings) {
+ return fmt.Sprintf("unknown event %d", e)
+ }
+ return eventStrings[e]
+}
+
// The event structure.
type yaml_event_t struct {
@@ -521,9 +543,9 @@ type yaml_parser_t struct {
read_handler yaml_read_handler_t // Read handler.
- input_file io.Reader // File input data.
- input []byte // String input data.
- input_pos int
+ input_reader io.Reader // File input data.
+ input []byte // String input data.
+ input_pos int
eof bool // EOF flag
@@ -632,7 +654,7 @@ type yaml_emitter_t struct {
write_handler yaml_write_handler_t // Write handler.
output_buffer *[]byte // String output data.
- output_file io.Writer // File output data.
+ output_writer io.Writer // File output data.
buffer []byte // The working buffer.
buffer_pos int // The current position of the buffer.