From 2ecac0a63c910cdc536a064d23361abcca61e303 Mon Sep 17 00:00:00 2001 From: ale <ale@incal.net> Date: Wed, 20 May 2020 21:35:20 +0100 Subject: [PATCH] Upgrade to elastic.v7 --- go.mod | 5 + go.sum | 62 ++ logcat.go | 4 +- vendor/github.com/mailru/easyjson/.gitignore | 6 + vendor/github.com/mailru/easyjson/.travis.yml | 12 + vendor/github.com/mailru/easyjson/Makefile | 93 +- vendor/github.com/mailru/easyjson/README.md | 3 + vendor/github.com/mailru/easyjson/go.mod | 3 + vendor/github.com/mailru/easyjson/helpers.go | 10 + .../mailru/easyjson/jlexer/lexer.go | 9 +- .../mailru/easyjson/jwriter/writer.go | 43 +- .../mailru/easyjson/unknown_fields.go | 34 + .../github.com/olivere/elastic/v7/.gitignore | 38 + .../olivere/elastic/v7/.travis.yml.off | 32 + .../olivere/elastic/v7}/CHANGELOG-3.0.md | 0 .../olivere/elastic/v7}/CHANGELOG-5.0.md | 0 .../olivere/elastic/v7}/CHANGELOG-6.0.md | 2 +- .../olivere/elastic/v7/CHANGELOG-7.0.md | 55 ++ .../olivere/elastic/v7}/CODE_OF_CONDUCT.md | 0 .../olivere/elastic/v7}/CONTRIBUTING.md | 6 +- .../olivere/elastic/v7}/CONTRIBUTORS | 58 +- .../olivere/elastic/v7}/ISSUE_TEMPLATE.md | 7 +- .../olivere/elastic/{ => v7}/LICENSE | 0 .../olivere/elastic/v7}/README.md | 89 +- .../elastic/v7}/acknowledged_response.go | 2 +- .../olivere/elastic/v7}/backoff.go | 0 .../olivere/elastic/v7}/bulk.go | 89 +- .../elastic/v7}/bulk_delete_request.go | 66 +- .../v7}/bulk_delete_request_easyjson.go | 78 +- .../olivere/elastic/v7}/bulk_index_request.go | 35 +- .../v7}/bulk_index_request_easyjson.go | 92 +- .../olivere/elastic/v7}/bulk_processor.go | 132 ++- .../olivere/elastic/v7}/bulk_request.go | 0 .../elastic/v7}/bulk_update_request.go | 50 +- .../v7}/bulk_update_request_easyjson.go | 98 +- .../olivere/elastic/v7}/canonicalize.go | 0 .../olivere/elastic/v7}/cat_aliases.go | 86 +- .../olivere/elastic/v7}/cat_allocation.go | 84 +- .../olivere/elastic/v7}/cat_count.go | 84 +- .../olivere/elastic/v7}/cat_health.go | 82 +- .../olivere/elastic/v7}/cat_indices.go | 254 ++++- .../olivere/elastic/v7/cat_shards.go | 387 ++++++++ .../olivere/elastic/v7}/clear_scroll.go | 84 +- .../olivere/elastic/v7}/client.go | 622 +++++++++---- .../olivere/elastic/v7}/cluster_health.go | 92 +- .../olivere/elastic/v7/cluster_reroute.go | 438 +++++++++ .../olivere/elastic/v7}/cluster_state.go | 135 ++- .../olivere/elastic/v7}/cluster_stats.go | 213 +++-- .../olivere/elastic/{ => v7}/config/config.go | 0 .../olivere/elastic/{ => v7}/config/doc.go | 0 .../olivere/elastic/v7}/connection.go | 0 .../olivere/elastic/v7}/count.go | 89 +- .../olivere/elastic/v7}/decoder.go | 12 + .../olivere/elastic/v7}/delete.go | 102 +- .../olivere/elastic/v7}/delete_by_query.go | 119 ++- .../olivere/elastic/v7}/doc.go | 0 .../olivere/elastic/v7/docker-compose.yml | 61 ++ .../olivere/elastic/v7/docvalue_field.go | 42 + .../olivere/elastic/v7}/errors.go | 49 +- .../olivere/elastic/v7}/exists.go | 80 +- .../olivere/elastic/v7}/explain.go | 110 ++- .../elastic/v7}/fetch_source_context.go | 6 +- .../olivere/elastic/v7}/field_caps.go | 81 +- .../olivere/elastic/v7}/geo_point.go | 0 .../olivere/elastic/v7}/get.go | 112 ++- vendor/github.com/olivere/elastic/v7/go.mod | 14 + .../olivere/elastic/v7}/highlight.go | 6 +- .../olivere/elastic/v7}/index.go | 109 ++- .../olivere/elastic/v7}/indices_analyze.go | 156 ++-- .../olivere/elastic/v7/indices_clear_cache.go | 240 +++++ .../olivere/elastic/v7}/indices_close.go | 81 +- .../olivere/elastic/v7/indices_create.go | 189 ++++ .../olivere/elastic/v7}/indices_delete.go | 81 +- .../elastic/v7}/indices_delete_template.go | 82 +- .../olivere/elastic/v7}/indices_exists.go | 75 +- .../elastic/v7}/indices_exists_template.go | 77 +- .../olivere/elastic/v7}/indices_flush.go | 83 +- .../elastic/v7/indices_flush_synced.go | 281 ++++++ .../olivere/elastic/v7}/indices_forcemerge.go | 92 +- .../olivere/elastic/v7/indices_freeze.go | 229 +++++ .../olivere/elastic/v7}/indices_get.go | 101 +- .../elastic/v7}/indices_get_aliases.go | 103 ++- .../elastic/v7}/indices_get_field_mapping.go | 81 +- .../elastic/v7}/indices_get_mapping.go | 81 +- .../elastic/v7}/indices_get_settings.go | 81 +- .../elastic/v7}/indices_get_template.go | 93 +- .../olivere/elastic/v7}/indices_open.go | 100 +- .../olivere/elastic/v7}/indices_put_alias.go | 86 +- .../elastic/v7}/indices_put_mapping.go | 111 ++- .../elastic/v7}/indices_put_settings.go | 83 +- .../elastic/v7}/indices_put_template.go | 84 +- .../olivere/elastic/v7/indices_refresh.go | 149 +++ .../olivere/elastic/v7}/indices_rollover.go | 84 +- .../olivere/elastic/v7}/indices_segments.go | 93 +- .../olivere/elastic/v7}/indices_shrink.go | 84 +- .../olivere/elastic/v7/indices_stats.go | 530 +++++++++++ .../olivere/elastic/v7/indices_unfreeze.go | 229 +++++ .../elastic/v7}/ingest_delete_pipeline.go | 82 +- .../elastic/v7}/ingest_get_pipeline.go | 90 +- .../elastic/v7}/ingest_put_pipeline.go | 84 +- .../elastic/v7}/ingest_simulate_pipeline.go | 88 +- .../olivere/elastic/v7}/inner_hit.go | 12 +- .../olivere/elastic/v7}/logger.go | 0 .../olivere/elastic/v7}/mget.go | 86 +- .../olivere/elastic/v7}/msearch.go | 83 +- .../olivere/elastic/v7}/mtermvectors.go | 75 +- .../olivere/elastic/v7}/nodes_info.go | 113 ++- .../olivere/elastic/v7}/nodes_stats.go | 114 ++- vendor/github.com/olivere/elastic/v7/ping.go | 197 ++++ .../olivere/elastic/v7}/plugins.go | 0 .../olivere/elastic/v7}/query.go | 0 .../olivere/elastic/v7}/reindex.go | 271 +++--- .../olivere/elastic/v7}/request.go | 0 .../olivere/elastic/v7}/rescore.go | 0 .../olivere/elastic/v7}/rescorer.go | 0 .../olivere/elastic/v7}/response.go | 29 +- .../olivere/elastic/v7}/retrier.go | 0 .../olivere/elastic/v7}/retry.go | 0 .../olivere/elastic/v7}/run-es.sh | 2 +- .../olivere/elastic/v7/run-tests.sh | 2 + .../olivere/elastic/v7}/script.go | 52 +- .../olivere/elastic/v7}/script_delete.go | 82 +- .../olivere/elastic/v7}/script_get.go | 84 +- .../olivere/elastic/v7}/script_put.go | 84 +- .../olivere/elastic/v7}/scroll.go | 205 ++++- .../github.com/olivere/elastic/v7/search.go | 868 ++++++++++++++++++ .../olivere/elastic/v7}/search_aggs.go | 610 +++++++----- .../search_aggs_bucket_adjacency_matrix.go | 2 +- .../search_aggs_bucket_auto_date_histogram.go | 163 ++++ .../v7}/search_aggs_bucket_children.go | 2 +- .../v7}/search_aggs_bucket_composite.go | 139 ++- .../search_aggs_bucket_count_thresholds.go | 0 .../v7}/search_aggs_bucket_date_histogram.go | 70 +- .../v7}/search_aggs_bucket_date_range.go | 2 +- .../search_aggs_bucket_diversified_sampler.go | 2 +- .../elastic/v7}/search_aggs_bucket_filter.go | 2 +- .../elastic/v7}/search_aggs_bucket_filters.go | 2 +- .../v7}/search_aggs_bucket_geo_distance.go | 2 +- .../v7}/search_aggs_bucket_geohash_grid.go | 4 +- .../elastic/v7}/search_aggs_bucket_global.go | 2 +- .../v7}/search_aggs_bucket_histogram.go | 2 +- .../v7}/search_aggs_bucket_ip_range.go | 2 +- .../elastic/v7}/search_aggs_bucket_missing.go | 2 +- .../elastic/v7}/search_aggs_bucket_nested.go | 2 +- .../elastic/v7}/search_aggs_bucket_range.go | 2 +- .../v7/search_aggs_bucket_rare_terms.go | 156 ++++ .../v7}/search_aggs_bucket_reverse_nested.go | 2 +- .../elastic/v7}/search_aggs_bucket_sampler.go | 2 +- .../search_aggs_bucket_significant_terms.go | 79 +- .../search_aggs_bucket_significant_text.go | 9 +- .../elastic/v7}/search_aggs_bucket_terms.go | 89 +- .../elastic/v7}/search_aggs_matrix_stats.go | 2 +- .../elastic/v7}/search_aggs_metrics_avg.go | 12 +- .../v7}/search_aggs_metrics_cardinality.go | 11 +- .../v7}/search_aggs_metrics_extended_stats.go | 20 +- .../v7}/search_aggs_metrics_geo_bounds.go | 2 +- .../v7}/search_aggs_metrics_geo_centroid.go | 2 +- .../elastic/v7}/search_aggs_metrics_max.go | 11 +- ..._aggs_metrics_median_absolute_deviation.go | 119 +++ .../elastic/v7}/search_aggs_metrics_min.go | 11 +- .../search_aggs_metrics_percentile_ranks.go | 11 +- .../v7}/search_aggs_metrics_percentiles.go | 56 +- .../v7/search_aggs_metrics_scripted_metric.go | 112 +++ .../elastic/v7}/search_aggs_metrics_stats.go | 11 +- .../elastic/v7}/search_aggs_metrics_sum.go | 11 +- .../v7}/search_aggs_metrics_top_hits.go | 20 +- .../v7}/search_aggs_metrics_value_count.go | 2 +- .../v7/search_aggs_metrics_weighted_avg.go | 156 ++++ .../v7}/search_aggs_pipeline_avg_bucket.go | 2 +- .../v7}/search_aggs_pipeline_bucket_script.go | 2 +- .../search_aggs_pipeline_bucket_selector.go | 2 +- .../v7}/search_aggs_pipeline_bucket_sort.go | 2 +- .../search_aggs_pipeline_cumulative_sum.go | 2 +- .../v7}/search_aggs_pipeline_derivative.go | 2 +- ...rch_aggs_pipeline_extended_stats_bucket.go | 107 +++ .../v7}/search_aggs_pipeline_max_bucket.go | 2 +- .../v7}/search_aggs_pipeline_min_bucket.go | 2 +- .../v7}/search_aggs_pipeline_mov_avg.go | 18 +- .../elastic/v7/search_aggs_pipeline_mov_fn.go | 132 +++ ...search_aggs_pipeline_percentiles_bucket.go | 2 +- .../v7}/search_aggs_pipeline_serial_diff.go | 2 +- .../v7}/search_aggs_pipeline_stats_bucket.go | 2 +- .../v7}/search_aggs_pipeline_sum_bucket.go | 2 +- .../elastic/v7}/search_collapse_builder.go | 2 +- .../elastic/v7}/search_queries_bool.go | 2 +- .../elastic/v7}/search_queries_boosting.go | 2 +- .../v7}/search_queries_common_terms.go | 6 +- .../v7}/search_queries_constant_score.go | 2 +- .../elastic/v7}/search_queries_dis_max.go | 2 +- .../search_queries_distance_feature_query.go | 119 +++ .../elastic/v7}/search_queries_exists.go | 4 +- .../olivere/elastic/v7}/search_queries_fsq.go | 3 +- .../v7}/search_queries_fsq_score_funcs.go | 28 +- .../elastic/v7}/search_queries_fuzzy.go | 2 +- .../v7}/search_queries_geo_bounding_box.go | 2 +- .../v7}/search_queries_geo_distance.go | 2 +- .../elastic/v7}/search_queries_geo_polygon.go | 2 +- .../elastic/v7}/search_queries_has_child.go | 2 +- .../elastic/v7}/search_queries_has_parent.go | 2 +- .../olivere/elastic/v7}/search_queries_ids.go | 5 +- .../elastic/v7/search_queries_interval.go | 52 ++ .../v7/search_queries_interval_filter.go | 175 ++++ .../search_queries_interval_rules_all_of.go | 82 ++ .../search_queries_interval_rules_any_of.go | 60 ++ .../v7/search_queries_interval_rules_match.go | 94 ++ .../search_queries_interval_rules_prefix.go | 57 ++ .../search_queries_interval_rules_wildcard.go | 57 ++ .../elastic/v7}/search_queries_match.go | 4 +- .../elastic/v7}/search_queries_match_all.go | 2 +- .../elastic/v7}/search_queries_match_none.go | 2 +- .../v7}/search_queries_match_phrase.go | 2 +- .../v7}/search_queries_match_phrase_prefix.go | 2 +- .../v7}/search_queries_more_like_this.go | 6 +- .../elastic/v7}/search_queries_multi_match.go | 7 +- .../elastic/v7}/search_queries_nested.go | 2 +- .../elastic/v7}/search_queries_parent_id.go | 2 +- .../elastic/v7}/search_queries_percolator.go | 56 +- .../elastic/v7}/search_queries_prefix.go | 2 +- .../v7}/search_queries_query_string.go | 2 +- .../elastic/v7}/search_queries_range.go | 2 +- .../elastic/v7}/search_queries_raw_string.go | 0 .../elastic/v7}/search_queries_regexp.go | 2 +- .../elastic/v7}/search_queries_script.go | 2 +- .../elastic/v7/search_queries_script_score.go | 110 +++ .../v7}/search_queries_simple_query_string.go | 2 +- .../elastic/v7}/search_queries_slice.go | 2 +- .../elastic/v7}/search_queries_term.go | 2 +- .../elastic/v7}/search_queries_terms.go | 2 +- .../elastic/v7}/search_queries_terms_set.go | 5 +- .../elastic/v7}/search_queries_type.go | 2 +- .../elastic/v7}/search_queries_wildcard.go | 2 +- .../elastic/v7}/search_queries_wrapper.go | 2 +- .../olivere/elastic/v7/search_request.go | 586 ++++++++++++ .../olivere/elastic/v7}/search_shards.go | 130 ++- .../olivere/elastic/v7}/search_source.go | 206 +++-- .../elastic/v7}/search_terms_lookup.go | 4 +- .../olivere/elastic/v7}/snapshot_create.go | 106 ++- .../elastic/v7}/snapshot_create_repository.go | 90 +- .../olivere/elastic/v7/snapshot_delete.go | 154 ++++ .../elastic/v7}/snapshot_delete_repository.go | 81 +- .../olivere/elastic/v7/snapshot_get.go | 225 +++++ .../elastic/v7}/snapshot_get_repository.go | 85 +- .../olivere/elastic/v7/snapshot_restore.go | 298 ++++++ .../olivere/elastic/v7/snapshot_status.go | 258 ++++++ .../elastic/v7}/snapshot_verify_repository.go | 82 +- .../olivere/elastic/v7}/sort.go | 94 +- .../olivere/elastic/v7}/suggest_field.go | 0 .../olivere/elastic/v7}/suggester.go | 0 .../elastic/v7}/suggester_completion.go | 9 +- .../olivere/elastic/v7}/suggester_context.go | 2 +- .../elastic/v7}/suggester_context_category.go | 39 +- .../elastic/v7}/suggester_context_geo.go | 100 +- .../olivere/elastic/v7}/suggester_phrase.go | 22 +- .../olivere/elastic/v7}/suggester_term.go | 4 +- .../olivere/elastic/v7/tasks_cancel.go | 207 +++++ .../olivere/elastic/v7/tasks_get_task.go | 169 ++++ .../olivere/elastic/v7}/tasks_list.go | 157 ++-- .../olivere/elastic/v7}/termvectors.go | 136 ++- .../github.com/olivere/elastic/v7/update.go | 412 +++++++++ .../olivere/elastic/v7}/update_by_query.go | 142 ++- .../elastic/{ => v7}/uritemplates/LICENSE | 0 .../{ => v7}/uritemplates/uritemplates.go | 2 +- .../elastic/{ => v7}/uritemplates/utils.go | 0 .../olivere/elastic/v7}/validate.go | 104 ++- .../elastic/v7/xpack_ilm_delete_lifecycle.go | 194 ++++ .../elastic/v7/xpack_ilm_get_lifecycle.go | 193 ++++ .../elastic/v7/xpack_ilm_put_lifecycle.go | 214 +++++ .../olivere/elastic/v7/xpack_info.go | 225 +++++ .../v7/xpack_security_change_password.go | 201 ++++ .../elastic/v7/xpack_security_delete_role.go | 159 ++++ .../v7/xpack_security_delete_role_mapping.go | 159 ++++ .../elastic/v7/xpack_security_delete_user.go | 170 ++++ .../elastic/v7/xpack_security_disable_user.go | 168 ++++ .../elastic/v7/xpack_security_enable_user.go | 168 ++++ .../elastic/v7/xpack_security_get_role.go | 186 ++++ .../v7/xpack_security_get_role_mapping.go | 165 ++++ .../elastic/v7/xpack_security_get_user.go | 176 ++++ .../elastic/v7/xpack_security_put_role.go | 174 ++++ .../v7/xpack_security_put_role_mapping.go | 174 ++++ .../elastic/v7/xpack_security_put_user.go | 215 +++++ .../elastic/v7/xpack_watcher_ack_watch.go | 198 ++++ .../v7/xpack_watcher_activate_watch.go | 169 ++++ .../v7/xpack_watcher_deactivate_watch.go | 169 ++++ .../elastic/v7/xpack_watcher_delete_watch.go | 171 ++++ .../elastic/v7/xpack_watcher_execute_watch.go | 214 +++++ .../elastic/v7/xpack_watcher_get_watch.go | 214 +++++ .../elastic/v7/xpack_watcher_put_watch.go | 212 +++++ .../olivere/elastic/v7/xpack_watcher_start.go | 137 +++ .../olivere/elastic/v7/xpack_watcher_stats.go | 165 ++++ .../olivere/elastic/v7/xpack_watcher_stop.go | 137 +++ vendor/github.com/pkg/errors/.gitignore | 24 + vendor/github.com/pkg/errors/.travis.yml | 10 + vendor/github.com/pkg/errors/Makefile | 44 + vendor/github.com/pkg/errors/README.md | 11 +- vendor/github.com/pkg/errors/errors.go | 51 +- vendor/github.com/pkg/errors/go113.go | 38 + vendor/github.com/pkg/errors/stack.go | 58 +- vendor/gopkg.in/olivere/elastic.v6/LICENSE | 20 - vendor/gopkg.in/olivere/elastic.v6/go.mod | 13 - .../olivere/elastic.v6/indices_create.go | 136 --- .../olivere/elastic.v6/indices_exists_type.go | 165 ---- .../olivere/elastic.v6/indices_refresh.go | 98 -- .../olivere/elastic.v6/indices_stats.go | 392 -------- vendor/gopkg.in/olivere/elastic.v6/ping.go | 127 --- vendor/gopkg.in/olivere/elastic.v6/search.go | 595 ------------ .../olivere/elastic.v6/search_request.go | 211 ----- .../olivere/elastic.v6/tasks_cancel.go | 149 --- .../olivere/elastic.v6/tasks_get_task.go | 108 --- vendor/gopkg.in/olivere/elastic.v6/update.go | 330 ------- vendor/modules.txt | 11 + vendor/vendor.json | 55 -- 311 files changed, 20772 insertions(+), 5000 deletions(-) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 vendor/github.com/mailru/easyjson/.gitignore create mode 100644 vendor/github.com/mailru/easyjson/.travis.yml create mode 100644 vendor/github.com/mailru/easyjson/go.mod create mode 100644 vendor/github.com/mailru/easyjson/unknown_fields.go create mode 100644 vendor/github.com/olivere/elastic/v7/.gitignore create mode 100644 vendor/github.com/olivere/elastic/v7/.travis.yml.off rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CHANGELOG-3.0.md (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CHANGELOG-5.0.md (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CHANGELOG-6.0.md (89%) create mode 100644 vendor/github.com/olivere/elastic/v7/CHANGELOG-7.0.md rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CODE_OF_CONDUCT.md (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CONTRIBUTING.md (88%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/CONTRIBUTORS (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/ISSUE_TEMPLATE.md (92%) rename vendor/github.com/olivere/elastic/{ => v7}/LICENSE (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/README.md (80%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/acknowledged_response.go (90%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/backoff.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk.go (83%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_delete_request.go (68%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_delete_request_easyjson.go (72%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_index_request.go (82%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_index_request_easyjson.go (72%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_processor.go (82%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_request.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_update_request.go (82%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/bulk_update_request_easyjson.go (82%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/canonicalize.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cat_aliases.go (65%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cat_allocation.go (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cat_count.go (65%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cat_health.go (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cat_indices.go (65%) create mode 100644 vendor/github.com/olivere/elastic/v7/cat_shards.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/clear_scroll.go (51%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/client.go (80%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cluster_health.go (77%) create mode 100644 vendor/github.com/olivere/elastic/v7/cluster_reroute.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cluster_state.go (64%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/cluster_stats.go (64%) rename vendor/github.com/olivere/elastic/{ => v7}/config/config.go (100%) rename vendor/github.com/olivere/elastic/{ => v7}/config/doc.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/connection.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/count.go (79%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/decoder.go (68%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/delete.go (65%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/delete_by_query.go (87%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/doc.go (100%) create mode 100644 vendor/github.com/olivere/elastic/v7/docker-compose.yml create mode 100644 vendor/github.com/olivere/elastic/v7/docvalue_field.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/errors.go (75%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/exists.go (65%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/explain.go (76%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/fetch_source_context.go (90%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/field_caps.go (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/geo_point.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/get.go (66%) create mode 100644 vendor/github.com/olivere/elastic/v7/go.mod rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/highlight.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/index.go (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_analyze.go (63%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_clear_cache.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_close.go (67%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_create.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_delete.go (59%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_delete_template.go (58%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_exists.go (66%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_exists_template.go (56%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_flush.go (69%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_flush_synced.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_forcemerge.go (70%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_freeze.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get.go (71%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get_aliases.go (55%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get_field_mapping.go (69%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get_mapping.go (68%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get_settings.go (70%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_get_template.go (54%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_open.go (59%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_put_alias.go (77%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_put_mapping.go (71%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_put_settings.go (71%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_put_template.go (71%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_refresh.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_rollover.go (78%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_segments.go (79%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/indices_shrink.go (68%) create mode 100644 vendor/github.com/olivere/elastic/v7/indices_stats.go create mode 100644 vendor/github.com/olivere/elastic/v7/indices_unfreeze.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/ingest_delete_pipeline.go (60%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/ingest_get_pipeline.go (52%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/ingest_put_pipeline.go (64%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/ingest_simulate_pipeline.go (63%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/inner_hit.go (89%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/logger.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/mget.go (75%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/msearch.go (55%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/mtermvectors.go (86%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/nodes_info.go (86%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/nodes_stats.go (89%) create mode 100644 vendor/github.com/olivere/elastic/v7/ping.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/plugins.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/query.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/reindex.go (75%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/request.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/rescore.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/rescorer.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/response.go (52%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/retrier.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/retry.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/run-es.sh (91%) mode change 100755 => 100644 create mode 100644 vendor/github.com/olivere/elastic/v7/run-tests.sh rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/script.go (69%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/script_delete.go (57%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/script_get.go (52%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/script_put.go (64%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/scroll.go (67%) create mode 100644 vendor/github.com/olivere/elastic/v7/search.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs.go (71%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_adjacency_matrix.go (97%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_auto_date_histogram.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_children.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_composite.go (78%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_count_thresholds.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_date_histogram.go (76%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_date_range.go (99%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_diversified_sampler.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_filter.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_filters.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_geo_distance.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_geohash_grid.go (94%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_global.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_histogram.go (99%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_ip_range.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_missing.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_nested.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_range.go (99%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_rare_terms.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_reverse_nested.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_sampler.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_significant_terms.go (80%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_significant_text.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_bucket_terms.go (82%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_matrix_stats.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_avg.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_cardinality.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_extended_stats.go (85%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_geo_bounds.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_geo_centroid.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_max.go (91%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_median_absolute_deviation.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_min.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_percentile_ranks.go (92%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_percentiles.go (69%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_scripted_metric.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_stats.go (90%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_sum.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_top_hits.go (86%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_metrics_value_count.go (97%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_weighted_avg.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_avg_bucket.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_bucket_script.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_bucket_selector.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_bucket_sort.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_cumulative_sum.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_derivative.go (97%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_extended_stats_bucket.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_max_bucket.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_min_bucket.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_mov_avg.go (93%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_fn.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_percentiles_bucket.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_serial_diff.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_stats_bucket.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_aggs_pipeline_sum_bucket.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_collapse_builder.go (94%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_bool.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_boosting.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_common_terms.go (93%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_constant_score.go (95%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_dis_max.go (97%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_distance_feature_query.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_exists.go (89%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_fsq.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_fsq_score_funcs.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_fuzzy.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_geo_bounding_box.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_geo_distance.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_geo_polygon.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_has_child.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_has_parent.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_ids.go (90%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_filter.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_all_of.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_any_of.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_match.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_prefix.go create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_wildcard.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_match.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_match_all.go (95%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_match_none.go (93%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_match_phrase.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_match_phrase_prefix.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_more_like_this.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_multi_match.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_nested.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_parent_id.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_percolator.go (69%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_prefix.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_query_string.go (99%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_range.go (98%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_raw_string.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_regexp.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_script.go (95%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_script_score.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_simple_query_string.go (99%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_slice.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_term.go (95%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_terms.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_terms_set.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_type.go (91%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_wildcard.go (96%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_queries_wrapper.go (92%) create mode 100644 vendor/github.com/olivere/elastic/v7/search_request.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_shards.go (56%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_source.go (72%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/search_terms_lookup.go (92%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/snapshot_create.go (66%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/snapshot_create_repository.go (69%) create mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_delete.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/snapshot_delete_repository.go (60%) create mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_get.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/snapshot_get_repository.go (60%) create mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_restore.go create mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_status.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/snapshot_verify_repository.go (59%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/sort.go (85%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggest_field.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_completion.go (95%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_context.go (97%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_context_category.go (74%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_context_geo.go (56%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_phrase.go (94%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/suggester_term.go (97%) create mode 100644 vendor/github.com/olivere/elastic/v7/tasks_cancel.go create mode 100644 vendor/github.com/olivere/elastic/v7/tasks_get_task.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/tasks_list.go (59%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/termvectors.go (79%) create mode 100644 vendor/github.com/olivere/elastic/v7/update.go rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/update_by_query.go (85%) rename vendor/github.com/olivere/elastic/{ => v7}/uritemplates/LICENSE (100%) rename vendor/github.com/olivere/elastic/{ => v7}/uritemplates/uritemplates.go (99%) rename vendor/github.com/olivere/elastic/{ => v7}/uritemplates/utils.go (100%) rename vendor/{gopkg.in/olivere/elastic.v6 => github.com/olivere/elastic/v7}/validate.go (73%) create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_delete_lifecycle.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_get_lifecycle.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_put_lifecycle.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_info.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_change_password.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_role.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_role_mapping.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_user.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_disable_user.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_enable_user.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_role.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_role_mapping.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_user.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_role.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_role_mapping.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_user.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_ack_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_activate_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_deactivate_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_delete_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_execute_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_get_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_put_watch.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_start.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_stats.go create mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_stop.go create mode 100644 vendor/github.com/pkg/errors/.gitignore create mode 100644 vendor/github.com/pkg/errors/.travis.yml create mode 100644 vendor/github.com/pkg/errors/Makefile create mode 100644 vendor/github.com/pkg/errors/go113.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/LICENSE delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/go.mod delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/indices_create.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/indices_exists_type.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/indices_refresh.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/indices_stats.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/ping.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/search.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/search_request.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/tasks_cancel.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/tasks_get_task.go delete mode 100644 vendor/gopkg.in/olivere/elastic.v6/update.go create mode 100644 vendor/modules.txt delete mode 100644 vendor/vendor.json diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..dc3a61d --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.autistici.org/ai3/tools/logcat + +// go: no requirements found in vendor/vendor.json + +require github.com/olivere/elastic/v7 v7.0.15 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..497b654 --- /dev/null +++ b/go.sum @@ -0,0 +1,62 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/aws/aws-sdk-go v1.30.7/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/mailru/easyjson v0.7.1 h1:mdxE1MF9o53iCb2Ghj1VfWvh7ZOwHpnVG/xwXrV90U8= +github.com/mailru/easyjson v0.7.1/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= +github.com/olivere/elastic/v7 v7.0.15 h1:v7kX5S+oMFfYKS4ZyzD37GH6lfZSpBo9atynRwBUywE= +github.com/olivere/elastic/v7 v7.0.15/go.mod h1:+FgncZ8ho1QF3NlBo77XbuoTKYHhvEOfFZKIAfHnnDE= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/logcat.go b/logcat.go index d92951a..05896fb 100644 --- a/logcat.go +++ b/logcat.go @@ -19,7 +19,7 @@ import ( "sync" "time" - "gopkg.in/olivere/elastic.v6" + "github.com/olivere/elastic/v7" ) var ( @@ -214,7 +214,7 @@ func runQuery(client *elastic.Client, query elastic.Query, indexes []string, w i return } for _, hit := range result.Hits.Hits { - jsonW.Push(*hit.Source) + jsonW.Push(hit.Source) } } }() diff --git a/vendor/github.com/mailru/easyjson/.gitignore b/vendor/github.com/mailru/easyjson/.gitignore new file mode 100644 index 0000000..fbfaf7a --- /dev/null +++ b/vendor/github.com/mailru/easyjson/.gitignore @@ -0,0 +1,6 @@ +.root +*_easyjson.go +*.iml +.idea +*.swp +bin/* diff --git a/vendor/github.com/mailru/easyjson/.travis.yml b/vendor/github.com/mailru/easyjson/.travis.yml new file mode 100644 index 0000000..0ececa0 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/.travis.yml @@ -0,0 +1,12 @@ +language: go + +go: + - tip + - stable + +matrix: + allow_failures: + - go: tip + +install: + - go get golang.org/x/lint/golint diff --git a/vendor/github.com/mailru/easyjson/Makefile b/vendor/github.com/mailru/easyjson/Makefile index 7cfec87..80449f0 100644 --- a/vendor/github.com/mailru/easyjson/Makefile +++ b/vendor/github.com/mailru/easyjson/Makefile @@ -1,61 +1,56 @@ -PKG=github.com/mailru/easyjson -GOPATH:=$(PWD)/.root:$(GOPATH) -export GOPATH - all: test -.root/src/$(PKG): - mkdir -p $@ - for i in $$PWD/* ; do ln -s $$i $@/`basename $$i` ; done - -root: .root/src/$(PKG) - clean: - rm -rf .root + rm -rf bin rm -rf tests/*_easyjson.go + rm -rf benchmark/*_easyjson.go build: - go build -i -o .root/bin/easyjson $(PKG)/easyjson - -generate: root build - .root/bin/easyjson -stubs \ - .root/src/$(PKG)/tests/snake.go \ - .root/src/$(PKG)/tests/data.go \ - .root/src/$(PKG)/tests/omitempty.go \ - .root/src/$(PKG)/tests/nothing.go \ - .root/src/$(PKG)/tests/named_type.go \ - .root/src/$(PKG)/tests/custom_map_key_type.go \ - .root/src/$(PKG)/tests/embedded_type.go - - .root/bin/easyjson -all .root/src/$(PKG)/tests/data.go - .root/bin/easyjson -all .root/src/$(PKG)/tests/nothing.go - .root/bin/easyjson -all .root/src/$(PKG)/tests/errors.go - .root/bin/easyjson -snake_case .root/src/$(PKG)/tests/snake.go - .root/bin/easyjson -omit_empty .root/src/$(PKG)/tests/omitempty.go - .root/bin/easyjson -build_tags=use_easyjson .root/src/$(PKG)/benchmark/data.go - .root/bin/easyjson .root/src/$(PKG)/tests/nested_easy.go - .root/bin/easyjson .root/src/$(PKG)/tests/named_type.go - .root/bin/easyjson .root/src/$(PKG)/tests/custom_map_key_type.go - .root/bin/easyjson .root/src/$(PKG)/tests/embedded_type.go - .root/bin/easyjson -disallow_unknown_fields .root/src/$(PKG)/tests/disallow_unknown.go - -test: generate root + go build -i -o ./bin/easyjson ./easyjson + +generate: build + bin/easyjson -stubs \ + ./tests/snake.go \ + ./tests/data.go \ + ./tests/omitempty.go \ + ./tests/nothing.go \ + ./tests/named_type.go \ + ./tests/custom_map_key_type.go \ + ./tests/embedded_type.go \ + ./tests/reference_to_pointer.go \ + ./tests/html.go \ + ./tests/unknown_fields.go \ + + bin/easyjson -all ./tests/data.go + bin/easyjson -all ./tests/nothing.go + bin/easyjson -all ./tests/errors.go + bin/easyjson -all ./tests/html.go + bin/easyjson -snake_case ./tests/snake.go + bin/easyjson -omit_empty ./tests/omitempty.go + bin/easyjson -build_tags=use_easyjson ./benchmark/data.go + bin/easyjson ./tests/nested_easy.go + bin/easyjson ./tests/named_type.go + bin/easyjson ./tests/custom_map_key_type.go + bin/easyjson ./tests/embedded_type.go + bin/easyjson ./tests/reference_to_pointer.go + bin/easyjson ./tests/key_marshaler_map.go + bin/easyjson -disallow_unknown_fields ./tests/disallow_unknown.go + bin/easyjson ./tests/unknown_fields.go + +test: generate go test \ - $(PKG)/tests \ - $(PKG)/jlexer \ - $(PKG)/gen \ - $(PKG)/buffer - go test -benchmem -tags use_easyjson -bench . $(PKG)/benchmark - golint -set_exit_status .root/src/$(PKG)/tests/*_easyjson.go - -bench-other: generate root - @go test -benchmem -bench . $(PKG)/benchmark - @go test -benchmem -tags use_ffjson -bench . $(PKG)/benchmark - @go test -benchmem -tags use_jsoniter -bench . $(PKG)/benchmark - @go test -benchmem -tags use_codec -bench . $(PKG)/benchmark + ./tests \ + ./jlexer \ + ./gen \ + ./buffer + cd benchmark && go test -benchmem -tags use_easyjson -bench . + golint -set_exit_status ./tests/*_easyjson.go + +bench-other: generate + cd benchmark && make bench-python: benchmark/ujson.sh -.PHONY: root clean generate test build +.PHONY: clean generate test build diff --git a/vendor/github.com/mailru/easyjson/README.md b/vendor/github.com/mailru/easyjson/README.md index 7fd7686..3bdcf2d 100644 --- a/vendor/github.com/mailru/easyjson/README.md +++ b/vendor/github.com/mailru/easyjson/README.md @@ -173,6 +173,9 @@ for more information. typically for many uses/protocols the final, marshaled length of the JSON needs to be known prior to sending the data. Currently this is not possible with easyjson's architecture. + +* easyjson parser and codegen based on reflection, so it wont works on `package main` + files, because they cant be imported by parser. ## Benchmarks diff --git a/vendor/github.com/mailru/easyjson/go.mod b/vendor/github.com/mailru/easyjson/go.mod new file mode 100644 index 0000000..7bc4a65 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/go.mod @@ -0,0 +1,3 @@ +module github.com/mailru/easyjson + +go 1.12 diff --git a/vendor/github.com/mailru/easyjson/helpers.go b/vendor/github.com/mailru/easyjson/helpers.go index b86b87d..04ac635 100644 --- a/vendor/github.com/mailru/easyjson/helpers.go +++ b/vendor/github.com/mailru/easyjson/helpers.go @@ -26,6 +26,16 @@ type Optional interface { IsDefined() bool } +// UnknownsUnmarshaler provides a method to unmarshal unknown struct fileds and save them as you want +type UnknownsUnmarshaler interface { + UnmarshalUnknown(in *jlexer.Lexer, key string) +} + +// UnknownsMarshaler provides a method to write additional struct fields +type UnknownsMarshaler interface { + MarshalUnknowns(w *jwriter.Writer, first bool) +} + // Marshal returns data as a single byte slice. Method is suboptimal as the data is likely to be copied // from a chain of smaller chunks. func Marshal(v Marshaler) ([]byte, error) { diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go index 51f0566..ddd376b 100644 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ b/vendor/github.com/mailru/easyjson/jlexer/lexer.go @@ -521,11 +521,12 @@ func (r *Lexer) SkipRecursive() { r.scanToken() var start, end byte - if r.token.delimValue == '{' { + switch r.token.delimValue { + case '{': start, end = '{', '}' - } else if r.token.delimValue == '[' { + case '[': start, end = '[', ']' - } else { + default: r.consume() return } @@ -1151,7 +1152,7 @@ func (r *Lexer) Interface() interface{} { } else if r.token.delimValue == '[' { r.consume() - var ret []interface{} + ret := []interface{}{} for !r.IsDelim(']') { ret = append(ret, r.Interface()) r.WantComma() diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go index b9ed7cc..eb8547c 100644 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ b/vendor/github.com/mailru/easyjson/jwriter/writer.go @@ -270,16 +270,25 @@ func (w *Writer) Bool(v bool) { const chars = "0123456789abcdef" -func isNotEscapedSingleChar(c byte, escapeHTML bool) bool { - // Note: might make sense to use a table if there are more chars to escape. With 4 chars - // it benchmarks the same. - if escapeHTML { - return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf - } else { - return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf +func getTable(falseValues ...int) [128]bool { + table := [128]bool{} + + for i := 0; i < 128; i++ { + table[i] = true + } + + for _, v := range falseValues { + table[v] = false } + + return table } +var ( + htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\') + htmlNoEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '\\') +) + func (w *Writer) String(s string) { w.Buffer.AppendByte('"') @@ -288,15 +297,23 @@ func (w *Writer) String(s string) { p := 0 // last non-escape symbol + var escapeTable [128]bool + if w.NoEscapeHTML { + escapeTable = htmlNoEscapeTable + } else { + escapeTable = htmlEscapeTable + } + for i := 0; i < len(s); { c := s[i] - if isNotEscapedSingleChar(c, !w.NoEscapeHTML) { - // single-width character, no escaping is required - i++ - continue - } else if c < utf8.RuneSelf { - // single-with character, need to escape + if c < utf8.RuneSelf { + if escapeTable[c] { + // single-width character, no escaping is required + i++ + continue + } + w.Buffer.AppendString(s[p:i]) switch c { case '\t': diff --git a/vendor/github.com/mailru/easyjson/unknown_fields.go b/vendor/github.com/mailru/easyjson/unknown_fields.go new file mode 100644 index 0000000..6cfdf83 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/unknown_fields.go @@ -0,0 +1,34 @@ +package easyjson + +import ( + json "encoding/json" + + jlexer "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// UnknownFieldsProxy implemets UnknownsUnmarshaler and UnknownsMarshaler +// use it as embedded field in your structure to parse and then serialize unknown struct fields +type UnknownFieldsProxy struct { + unknownFields map[string]interface{} +} + +func (s *UnknownFieldsProxy) UnmarshalUnknown(in *jlexer.Lexer, key string) { + if s.unknownFields == nil { + s.unknownFields = make(map[string]interface{}, 1) + } + s.unknownFields[key] = in.Interface() +} + +func (s UnknownFieldsProxy) MarshalUnknowns(out *jwriter.Writer, first bool) { + for key, val := range s.unknownFields { + if first { + first = false + } else { + out.RawByte(',') + } + out.String(string(key)) + out.RawByte(':') + out.Raw(json.Marshal(val)) + } +} diff --git a/vendor/github.com/olivere/elastic/v7/.gitignore b/vendor/github.com/olivere/elastic/v7/.gitignore new file mode 100644 index 0000000..caa3019 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/.gitignore @@ -0,0 +1,38 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +.envrc + +/.vscode/ +/.idea/ +/debug.test +/generator +/cluster-test/cluster-test +/cluster-test/*.log +/cluster-test/es-chaos-monkey +/dist +/go.sum +/spec +/tmp +/CHANGELOG-3.0.html + diff --git a/vendor/github.com/olivere/elastic/v7/.travis.yml.off b/vendor/github.com/olivere/elastic/v7/.travis.yml.off new file mode 100644 index 0000000..b657308 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/.travis.yml.off @@ -0,0 +1,32 @@ +sudo: required +language: go +go: +- "1.13.x" +- "1.14.x" +- tip +matrix: + allow_failures: + - go: tip +env: +- GO111MODULE=on +- GO111MODULE=off +addons: + apt: + update: true + packages: + - docker-ce +services: +- docker +before_install: +- if [[ "$TRAVIS_OS_NAME" == "linux" && ! $(which nc) ]] ; then sudo apt-get install -y netcat ; fi +- sudo sysctl -w vm.max_map_count=262144 +- docker-compose pull +- docker-compose up -d +- go get -u github.com/google/go-cmp/cmp +- go get -u github.com/fortytw2/leaktest +- go get . ./aws/... ./config/... ./trace/... ./uritemplates/... +- while ! nc -z localhost 9200; do sleep 1; done +- while ! nc -z localhost 9210; do sleep 1; done +install: true # ignore the go get -t -v ./... +script: +- go test -race -deprecations -strict-decoder -v . ./aws/... ./config/... ./trace/... ./uritemplates/... diff --git a/vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-3.0.md b/vendor/github.com/olivere/elastic/v7/CHANGELOG-3.0.md similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-3.0.md rename to vendor/github.com/olivere/elastic/v7/CHANGELOG-3.0.md diff --git a/vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-5.0.md b/vendor/github.com/olivere/elastic/v7/CHANGELOG-5.0.md similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-5.0.md rename to vendor/github.com/olivere/elastic/v7/CHANGELOG-5.0.md diff --git a/vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-6.0.md b/vendor/github.com/olivere/elastic/v7/CHANGELOG-6.0.md similarity index 89% rename from vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-6.0.md rename to vendor/github.com/olivere/elastic/v7/CHANGELOG-6.0.md index 2779259..255bda4 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/CHANGELOG-6.0.md +++ b/vendor/github.com/olivere/elastic/v7/CHANGELOG-6.0.md @@ -14,5 +14,5 @@ Only use `true` or `false` for boolean values, not `0` or `1` or `on` or `off`. 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). +See [here for details](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/removal-of-types.html#_what_are_mapping_types). diff --git a/vendor/github.com/olivere/elastic/v7/CHANGELOG-7.0.md b/vendor/github.com/olivere/elastic/v7/CHANGELOG-7.0.md new file mode 100644 index 0000000..1edd9dd --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/CHANGELOG-7.0.md @@ -0,0 +1,55 @@ +# Changes from 6.0 to 7.0 + +See [breaking changes](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/breaking-changes-7.0.html). + +## SearchHit.Source changed from `*json.RawMessage` to `json.RawMessage` + +The `SearchHit` structure changed from + +``` +// SearchHit is a single hit. +type SearchHit struct { + ... + Source *json.RawMessage `json:"_source,omitempty"` // stored document source + ... +} +``` + +to + +``` +// SearchHit is a single hit. +type SearchHit struct { + ... + Source json.RawMessage `json:"_source,omitempty"` // stored document source + ... +} +``` + +As `json.RawMessage` is a `[]byte`, there is no need to specify it +as `*json.RawMessage` as `json.RawMessage` is perfectly ok to represent +a `nil` value. + +So when deserializing the search hits, you need to change your code from: + +``` +for _, hit := range searchResult.Hits.Hits { + var doc Doc + err := json.Unmarshal(*hit.Source, &doc) // notice the * here + if err != nil { + // Deserialization failed + } +} +``` + +to + +``` +for _, hit := range searchResult.Hits.Hits { + var doc Doc + err := json.Unmarshal(hit.Source, &doc) // it's missing here + if err != nil { + // Deserialization failed + } +} +``` diff --git a/vendor/gopkg.in/olivere/elastic.v6/CODE_OF_CONDUCT.md b/vendor/github.com/olivere/elastic/v7/CODE_OF_CONDUCT.md similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/CODE_OF_CONDUCT.md rename to vendor/github.com/olivere/elastic/v7/CODE_OF_CONDUCT.md diff --git a/vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTING.md b/vendor/github.com/olivere/elastic/v7/CONTRIBUTING.md similarity index 88% rename from vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTING.md rename to vendor/github.com/olivere/elastic/v7/CONTRIBUTING.md index 4fbc79d..c7c425a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTING.md +++ b/vendor/github.com/olivere/elastic/v7/CONTRIBUTING.md @@ -18,7 +18,7 @@ that we missed some features or changes. Feel free to change that. To make it easy to review and understand your changes, please keep the following things in mind before submitting your pull request: -* You compared the existing implemenation with the Java API, did you? +* You compared the existing implementation with the Java API, did you? * Please work on the latest possible state of `olivere/elastic`. Use `release-branch.v2` for targeting Elasticsearch 1.x and `release-branch.v3` for targeting 2.x. @@ -36,5 +36,5 @@ following things in mind before submitting your pull request: ## Additional Resources -* [GitHub documentation](http://help.github.com/) -* [GitHub pull request documentation](http://help.github.com/send-pull-requests/) +* [GitHub documentation](https://help.github.com/) +* [GitHub pull request documentation](https://help.github.com/en/articles/creating-a-pull-request) diff --git a/vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTORS b/vendor/github.com/olivere/elastic/v7/CONTRIBUTORS similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTORS rename to vendor/github.com/olivere/elastic/v7/CONTRIBUTORS index 1beea08..93f2d9e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/CONTRIBUTORS +++ b/vendor/github.com/olivere/elastic/v7/CONTRIBUTORS @@ -7,53 +7,80 @@ # Please keep this list sorted. 0x6875790d0a [@huydx](https://github.com/huydx) +Aaron Tami [@aarontami](https://github.com/aarontami) Adam Alix [@adamalix](https://github.com/adamalix) Adam Weiner [@adamweiner](https://github.com/adamweiner) Adrian Lungu [@AdrianLungu](https://github.com/AdrianLungu) alehano [@alehano](https://github.com/alehano) +Alejandro Carstens [@alejandro-carstens](https://github.com/alejandro-carstens) Alex [@akotlar](https://github.com/akotlar) Alexander Sack [@asac](https://github.com/asac) Alexandre Olivier [@aliphen](https://github.com/aliphen) Alexey Sharov [@nizsheanez](https://github.com/nizsheanez) +Aman Jain [@amanjain97](https://github.com/amanjain97) +Anders [@ANerd](https://github.com/ANerd) AndreKR [@AndreKR](https://github.com/AndreKR) André Bierlein [@ligustah](https://github.com/ligustah) Andrew Dunham [@andrew-d](https://github.com/andrew-d) Andrew Gaul [@andrewgaul](https://github.com/andrewgaul) Andy Walker [@alaska](https://github.com/alaska) +Arpit Agarwal [@arpiagar](https://github.com/arpiagar) Arquivei [@arquivei](https://github.com/arquivei) +Artemiy Elozhenko [@artezh](https://github.com/artezh) arthurgustin [@arthurgustin](https://github.com/arthurgustin) +Bas van Dijk [@basvandijk](https://github.com/basvandijk) Benjamin Fernandes [@LotharSee](https://github.com/LotharSee) Benjamin Zarzycki [@kf6nux](https://github.com/kf6nux) +Björn Gerdau [@kernle32dll](https://github.com/kernle32dll) Boris Popovschi [@Zyqsempai](https://github.com/Zyqsempai) +Bowei Xu [@vancexu](https://github.com/vancexu) Braden Bassingthwaite [@bbassingthwaite-va](https://github.com/bbassingthwaite-va) Brady Love [@bradylove](https://github.com/bradylove) Bryan Conklin [@bmconklin](https://github.com/bmconklin) Bruce Zhou [@brucez-isell](https://github.com/brucez-isell) +Carl Dunham [@carldunham](https://github.com/carldunham) +Carl Johan Gustavsson [@cjgu](https://github.com/cjgu) +Cat [@cat-turner](https://github.com/cat-turner) César Jiménez [@cesarjimenez](https://github.com/cesarjimenez) cforbes [@cforbes](https://github.com/cforbes) +張泰瑋(Chang Tai Wei) [@david30907d](https://github.com/david30907d) +cheshire [@NikitaSerenko](https://github.com/NikitaSerenko) Chris M [@tebriel](https://github.com/tebriel) Chris Rice [@donutmonger](https://github.com/donutmonger) Claudiu Olteanu [@claudiuolteanu](https://github.com/claudiuolteanu) Chris Duncan [@veqryn](https://github.com/veqryn) +Chris Ludden [@cludden](https://github.com/cludden) Christophe Courtaut [@kri5](https://github.com/kri5) +cmitchell [@cmitchell](https://github.com/cmitchell) Connor Peet [@connor4312](https://github.com/connor4312) Conrad Pankoff [@deoxxa](https://github.com/deoxxa) Corey Scott [@corsc](https://github.com/corsc) +Chris Petersen [@ex-nerd](https://github.com/ex-nerd) Daniel Barrett [@shendaras](https://github.com/shendaras) Daniel Heckrath [@DanielHeckrath](https://github.com/DanielHeckrath) Daniel Imfeld [@dimfeld](https://github.com/dimfeld) +Daniel Santos [@danlsgiga](https://github.com/danlsgiga) David Emanuel Buchmann [@wuurrd](https://github.com/wuurrd) +diacone [@diacone](https://github.com/diacone) +Diego Becciolini [@itizir](https://github.com/itizir) Dwayne Schultz [@myshkin5](https://github.com/myshkin5) +Elizabeth Jarrett [@mejarrett](https://github.com/mejarrett) +Elliot Williams [@elliotwms](https://github.com/elliotwms) Ellison Leão [@ellisonleao](https://github.com/ellisonleao) +Emil Gedda [@EmilGedda](https://github.com/EmilGedda) +Erik Grinaker [@erikgrinaker](https://github.com/erikgrinaker) Erwin [@eticzon](https://github.com/eticzon) +Etienne Lafarge [@elafarge](https://github.com/elafarge) Eugene Egorov [@EugeneEgorov](https://github.com/EugeneEgorov) 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) +Garrett Kelley [@GarrettKelley](https://github.com/GarrettKelley) Gaspard Douady [@plopik](https://github.com/plopik) Gaylord Aulke [@blafasel42](https://github.com/blafasel42) Gerhard Häring [@ghaering](https://github.com/ghaering) +gregoryfranklin [@gregoryfranklin](https://github.com/gregoryfranklin) Guilherme Silveira [@guilherme-santos](https://github.com/guilherme-santos) Guillaume J. Charmes [@creack](https://github.com/creack) Guiseppe [@gm42](https://github.com/gm42) @@ -61,16 +88,22 @@ Han Yu [@MoonighT](https://github.com/MoonighT) Harmen [@alicebob](https://github.com/alicebob) Harrison Wright [@wright8191](https://github.com/wright8191) Henry Clifford [@hcliff](https://github.com/hcliff) +Henry Stern [@hstern](https://github.com/hstern) Igor Dubinskiy [@idubinskiy](https://github.com/idubinskiy) initialcontext [@initialcontext](https://github.com/initialcontext) Isaac Saldana [@isaldana](https://github.com/isaldana) +Ishan Jain [@ishanjain28](https://github.com/ishanjain28) J Barkey Wolf [@jjhbw](https://github.com/jjhbw) Jack Lindamood [@cep21](https://github.com/cep21) Jacob [@jdelgad](https://github.com/jdelgad) +Jan Düpmeier [@jduepmeier](https://github.com/jduepmeier) Jayme Rotsaert [@jrots](https://github.com/jrots) +Jean-Alexandre Beaumont [@Enteris](https://github.com/Enteris) +Jean-François Roche [@jfroche](https://github.com/jfroche) Jeff Rand [@jeffrand](https://github.com/jeffrand) Jeremy Canady [@jrmycanady](https://github.com/jrmycanady) Jérémie Vexiau [@texvex](https://github.com/texvex) +Jesper Bränn [@Yopi](https://github.com/Yopi) Jim Berlage [@jimberlage](https://github.com/jimberlage) Joe Buck [@four2five](https://github.com/four2five) John Barker [@j16r](https://github.com/j16r) @@ -78,51 +111,69 @@ John Goodall [@jgoodall](https://github.com/jgoodall) John Stanford [@jxstanford](https://github.com/jxstanford) Jonas Groenaas Drange [@semafor](https://github.com/semafor) Josef Fröhle [@Dexus](https://github.com/Dexus) +José Martínez [@xose](https://github.com/xose) Josh Chorlton [@jchorl](https://github.com/jchorl) +Jpnock [@Jpnock](https://github.com/Jpnock) jun [@coseyo](https://github.com/coseyo) Junpei Tsuji [@jun06t](https://github.com/jun06t) +Karen Yang [@kyangtt](https://github.com/kyangtt) kartlee [@kartlee](https://github.com/kartlee) Keith Hatton [@khatton-ft](https://github.com/khatton-ft) kel [@liketic](https://github.com/liketic) Kenta SUZUKI [@suzuken](https://github.com/suzuken) Kevin Mulvey [@kmulvey](https://github.com/kmulvey) Kyle Brandt [@kylebrandt](https://github.com/kylebrandt) +Larry Cinnabar [@larrycinnabar](https://github.com/larrycinnabar) Leandro Piccilli [@lpic10](https://github.com/lpic10) Lee [@leezhm](https://github.com/leezhm) +lechnertech [@lechnertech](https://github.com/lechnertech) M. Zulfa Achsani [@misterciput](https://github.com/misterciput) Maciej Lisiewski [@c2h5oh](https://github.com/c2h5oh) Mara Kim [@autochthe](https://github.com/autochthe) Marcy Buccellato [@marcybuccellato](https://github.com/marcybuccellato) Mark Costello [@mcos](https://github.com/mcos) Martin Häger [@protomouse](https://github.com/protomouse) +Matt Braymer-Hayes [@mattayes](https://github.com/mattayes) Medhi Bechina [@mdzor](https://github.com/mdzor) Mike Beshai [@mbesh](https://github.com/mbesh) mmfrb [@mmfrb](https://github.com/mmfrb) mnpritula [@mnpritula](https://github.com/mnpritula) mosa [@mosasiru](https://github.com/mosasiru) +Muhammet Çakır [@cakirmuha](https://github.com/cakirmuha) naimulhaider [@naimulhaider](https://github.com/naimulhaider) Naoya Yoshizawa [@azihsoyn](https://github.com/azihsoyn) navins [@ishare](https://github.com/ishare) Naoya Tsutsumi [@tutuming](https://github.com/tutuming) +Nathan Lacey [@nlacey](https://github.com/nlacey) NeoCN [@NeoCN](https://github.com/NeoCN) Nicholas Wolff [@nwolff](https://github.com/nwolff) Nick K [@utrack](https://github.com/utrack) Nick Whyte [@nickw444](https://github.com/nickw444) Nicolae Vartolomei [@nvartolomei](https://github.com/nvartolomei) +okhowang [@okhowang](https://github.com/okhowang) Orne Brocaar [@brocaar](https://github.com/brocaar) Paul [@eyeamera](https://github.com/eyeamera) +Paul Oldenburg [@lr-paul](https://github.com/lr-paul) +Pedro [@otherview](https://github.com/otherview) Pete C [@peteclark-ft](https://github.com/peteclark-ft) +Peter Nagy [@nagypeterjob](https://github.com/nagypeterjob) Paolo [@ppiccolo](https://github.com/ppiccolo) -Radoslaw Wesolowski [r--w](https://github.com/r--w) +Igor Panychek [@panychek](https://github.com/panychek) +Radoslaw Wesolowski [@r--w](https://github.com/r--w) +Rafał Gałus [@rgalus](https://github.com/rgalus) rchicoli [@rchicoli](https://github.com/rchicoli) Roman Colohanin [@zuzmic](https://github.com/zuzmic) Ryan Schmukler [@rschmukler](https://github.com/rschmukler) Ryan Wynn [@rwynn](https://github.com/rwynn) Sacheendra talluri [@sacheendra](https://github.com/sacheendra) Sean DuBois [@Sean-Der](https://github.com/Sean-Der) +Sagan Yaroslav [@sgnrslv](https://github.com/sgnrslv) Shalin LK [@shalinlk](https://github.com/shalinlk) +Simon Schneider [@raynigon](https://github.com/raynigon) singham [@zhaochenxiao90](https://github.com/zhaochenxiao90) Slawomir CALUCH [@slawo](https://github.com/slawo) +soarpenguin [@soarpenguin](https://github.com/soarpenguin) +Stephan Krynauw [@skrynauw](https://github.com/skrynauw) Stephen Kubovic [@stephenkubovic](https://github.com/stephenkubovic) Stuart Warren [@Woz](https://github.com/stuart-warren) Sulaiman [@salajlan](https://github.com/salajlan) @@ -130,15 +181,18 @@ Sundar [@sundarv85](https://github.com/sundarv85) Swarlston [@Swarlston](https://github.com/Swarlston) Take [ww24](https://github.com/ww24) Tetsuya Morimoto [@t2y](https://github.com/t2y) +TheZeroSlave [@TheZeroSlave](https://github.com/TheZeroSlave) +Tomasz Elendt [@telendt](https://github.com/telendt) TimeEmit [@TimeEmit](https://github.com/timeemit) TusharM [@tusharm](https://github.com/tusharm) wangtuo [@wangtuo](https://github.com/wangtuo) Wédney Yuri [@wedneyyuri](https://github.com/wedneyyuri) +Wesley Kim [@wesleyk](https://github.com/wesleyk) wolfkdy [@wolfkdy](https://github.com/wolfkdy) Wyndham Blanton [@wyndhblb](https://github.com/wyndhblb) Yarden Bar [@ayashjorden](https://github.com/ayashjorden) -zakthomas [@zakthomas](https://github.com/zakthomas) Yuya Kusakabe [@higebu](https://github.com/higebu) +zakthomas [@zakthomas](https://github.com/zakthomas) Zach [@snowzach](https://github.com/snowzach) zhangxin [@visaxin](https://github.com/visaxin) @林 [@zplzpl](https://github.com/zplzpl) diff --git a/vendor/gopkg.in/olivere/elastic.v6/ISSUE_TEMPLATE.md b/vendor/github.com/olivere/elastic/v7/ISSUE_TEMPLATE.md similarity index 92% rename from vendor/gopkg.in/olivere/elastic.v6/ISSUE_TEMPLATE.md rename to vendor/github.com/olivere/elastic/v7/ISSUE_TEMPLATE.md index 88d66cc..11d6e2c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/ISSUE_TEMPLATE.md +++ b/vendor/github.com/olivere/elastic/v7/ISSUE_TEMPLATE.md @@ -3,10 +3,11 @@ your issue/question without further inquiry. Thank you. ### Which version of Elastic are you using? -[ ] elastic.v2 (for Elasticsearch 1.x) -[ ] elastic.v3 (for Elasticsearch 2.x) -[ ] elastic.v5 (for Elasticsearch 5.x) +[ ] elastic.v7 (for Elasticsearch 7.x) [ ] elastic.v6 (for Elasticsearch 6.x) +[ ] elastic.v5 (for Elasticsearch 5.x) +[ ] elastic.v3 (for Elasticsearch 2.x) +[ ] elastic.v2 (for Elasticsearch 1.x) ### Please describe the expected behavior diff --git a/vendor/github.com/olivere/elastic/LICENSE b/vendor/github.com/olivere/elastic/v7/LICENSE similarity index 100% rename from vendor/github.com/olivere/elastic/LICENSE rename to vendor/github.com/olivere/elastic/v7/LICENSE diff --git a/vendor/gopkg.in/olivere/elastic.v6/README.md b/vendor/github.com/olivere/elastic/v7/README.md similarity index 80% rename from vendor/gopkg.in/olivere/elastic.v6/README.md rename to vendor/github.com/olivere/elastic/v7/README.md index 9df2b56..2f2b073 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/README.md +++ b/vendor/github.com/olivere/elastic/v7/README.md @@ -1,29 +1,29 @@ # Elastic -**This is a development branch that is actively being worked on. DO NOT USE IN PRODUCTION! If you want to use stable versions of Elastic, please use a dependency manager like [dep](https://github.com/golang/dep).** +**This is a development branch that is actively being worked on. DO NOT USE IN PRODUCTION! If you want to use stable versions of Elastic, please use Go modules for the 7.x release (or later) or a dependency manager like [dep](https://github.com/golang/dep) for earlier releases.** Elastic is an [Elasticsearch](http://www.elasticsearch.org/) client for the [Go](http://www.golang.org/) programming language. -[](https://travis-ci.org/olivere/elastic) -[](http://godoc.org/github.com/olivere/elastic) +[](https://github.com/olivere/elastic/actions) +[](https://pkg.go.dev/github.com/olivere/elastic/v7?tab=doc) [](https://raw.githubusercontent.com/olivere/elastic/master/LICENSE) See the [wiki](https://github.com/olivere/elastic/wiki) for additional information about Elastic. <a href="https://www.buymeacoffee.com/Bjd96U8fm" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a> - ## 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.v7`](https://github.com/olivere/elastic/tree/release-branch.v7)) 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 Go modules.** Here's the version matrix: Elasticsearch version | Elastic version | Package URL | Remarks | ----------------------|------------------|-------------|---------| +7.x | 7.0 | [`github.com/olivere/elastic/v7`](https://github.com/olivere/elastic) ([source](https://github.com/olivere/elastic/tree/release-branch.v7) [doc](http://godoc.org/github.com/olivere/elastic)) | Use Go modules. 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. @@ -32,27 +32,32 @@ Elasticsearch version | Elastic version | Package URL | Remarks | **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 7.0.0 and want to use Elastic. +As listed above, you should use Elastic 7.0 (code is in `release-branch.v7`). -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`. +To use the required version of Elastic in your application, you +should use [Go modules](https://github.com/golang/go/wiki/Modules) +to manage dependencies. Make sure to use a version such as `7.0.0` or later. -To use Elastic, simply import: +To use Elastic, import: ```go -import "github.com/olivere/elastic" +import "github.com/olivere/elastic/v7" ``` +### Elastic 7.0 + +Elastic 7.0 targets Elasticsearch 7.x which [was released on April 10th 2019](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/release-notes-7.0.0.html). + +As always with major version, there are a lot of [breaking changes](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/release-notes-7.0.0.html#breaking-7.0.0). +We will use this as an opportunity to [clean up and refactor Elastic](https://github.com/olivere/elastic/blob/release-branch.v7/CHANGELOG-7.0.md), +as we already did in earlier (major) releases. + ### 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.2/breaking-changes-6.0.html) +Notice that there are a lot of [breaking changes in Elasticsearch 6.0](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/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. @@ -100,12 +105,10 @@ Having said that, there have been no big API changes that required you to rewrite your application big time. More often than not it's renaming APIs and adding/removing features so that Elastic is in sync with Elasticsearch. -Elastic has been used in production starting with Elasticsearch 0.90 up to recent 6.x -versions. Furthermore, we use [Travis CI](https://travis-ci.org/) -to test Elastic with the most recent versions of Elasticsearch and Go. -See the [.travis.yml](https://github.com/olivere/elastic/blob/master/.travis.yml) -file for the exact matrix and [Travis](https://travis-ci.org/olivere/elastic) -for the results. +Elastic has been used in production starting with Elasticsearch 0.90 up to recent 7.x +versions. +We recently switched to [GitHub Actions for testing](https://github.com/olivere/elastic/actions). +Before that, we used [Travis CI](https://travis-ci.org/olivere/elastic) successfully for years). Elasticsearch has quite a few features. Most of them are implemented by Elastic. I add features and APIs as required. It's straightforward @@ -129,8 +132,8 @@ Here's a [link to a complete working example for v6](https://gist.github.com/oli Here are a few tips on how to get used to Elastic: 1. Head over to the [Wiki](https://github.com/olivere/elastic/wiki) for detailed information and - topics like e.g. [how to add a middleware](/olivere/elastic/wiki/HttpTransport) - or how to [connect to AWS](/olivere/elastic/wiki/Using-with-AWS-Elasticsearch-Service). + topics like e.g. [how to add a middleware](https://github.com/olivere/elastic/wiki/HttpTransport) + or how to [connect to AWS](https://github.com/olivere/elastic/wiki/Using-with-AWS-Elasticsearch-Service). 2. If you are unsure how to implement something, read the tests (all `_test.go` files). They not only serve as a guard against changes, but also as a reference. 3. The [recipes](https://github.com/olivere/elastic/tree/release-branch.v6/recipes) @@ -191,6 +194,7 @@ Here are a few tips on how to get used to Elastic: - Bucket Aggregations - [x] Adjacency Matrix - [x] Children + - [x] Auto-interval Date Histogram - [x] Date Histogram - [x] Date Range - [x] Diversified Sampler @@ -252,22 +256,33 @@ Here are a few tips on how to get used to Elastic: - [x] Indices Segments - [ ] Indices Recovery - [ ] Indices Shard Stores -- [ ] Clear Cache +- [x] Clear Cache - [x] Flush - [x] Synced Flush - [x] Refresh - [x] Force Merge -### cat APIs +### Index Lifecycle Management APIs + +- [x] Create Policy +- [x] Get Policy +- [x] Delete Policy +- [ ] Move to Step +- [ ] Remove Policy +- [ ] Retry Policy +- [ ] Get Ilm Status +- [ ] Explain Lifecycle +- [ ] Start Ilm +- [ ] Stop Ilm -The cat APIs are not implemented as of now. We think they are better suited for operating with Elasticsearch on the command line. +### cat APIs -- [ ] cat aliases -- [ ] cat allocation -- [ ] cat count +- [X] cat aliases +- [X] cat allocation +- [X] cat count - [ ] cat fielddata -- [ ] cat health -- [ ] cat indices +- [X] cat health +- [X] cat indices - [ ] cat master - [ ] cat nodeattrs - [ ] cat nodes @@ -287,7 +302,7 @@ The cat APIs are not implemented as of now. We think they are better suited for - [x] Cluster State - [x] Cluster Stats - [ ] Pending Cluster Tasks -- [ ] Cluster Reroute +- [x] Cluster Reroute - [ ] Cluster Update Settings - [x] Nodes Stats - [x] Nodes Info @@ -338,8 +353,10 @@ The cat APIs are not implemented as of now. We think they are better suited for - [x] Geo Distance Query - [x] Geo Polygon Query - Specialized queries + - [x] Distance Feature Query - [x] More Like This Query - [x] Script Query + - [x] Script Score Query - [x] Percolate Query - Span queries - [ ] Span Term Query @@ -358,7 +375,9 @@ The cat APIs are not implemented as of now. We think they are better suited for - Snapshot and Restore - [x] Repositories - - [x] Snapshot + - [x] Snapshot get + - [x] Snapshot create + - [x] Snapshot delete - [ ] Restore - [ ] Snapshot status - [ ] Monitoring snapshot/restore status diff --git a/vendor/gopkg.in/olivere/elastic.v6/acknowledged_response.go b/vendor/github.com/olivere/elastic/v7/acknowledged_response.go similarity index 90% rename from vendor/gopkg.in/olivere/elastic.v6/acknowledged_response.go rename to vendor/github.com/olivere/elastic/v7/acknowledged_response.go index 2045ab8..a203c22 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/acknowledged_response.go +++ b/vendor/github.com/olivere/elastic/v7/acknowledged_response.go @@ -5,7 +5,7 @@ package elastic // AcknowledgedResponse is returned from various APIs. It simply indicates -// whether the operation is ack'd or not. +// whether the operation is acknowledged or not. type AcknowledgedResponse struct { Acknowledged bool `json:"acknowledged"` ShardsAcknowledged bool `json:"shards_acknowledged"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/backoff.go b/vendor/github.com/olivere/elastic/v7/backoff.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/backoff.go rename to vendor/github.com/olivere/elastic/v7/backoff.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk.go b/vendor/github.com/olivere/elastic/v7/bulk.go similarity index 83% rename from vendor/gopkg.in/olivere/elastic.v6/bulk.go rename to vendor/github.com/olivere/elastic/v7/bulk.go index 32b74cb..9ffe880 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk.go +++ b/vendor/github.com/olivere/elastic/v7/bulk.go @@ -5,13 +5,14 @@ package elastic import ( - "bytes" "context" "errors" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // BulkService allows for batching bulk requests and sending them to @@ -23,12 +24,18 @@ 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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for more details. type BulkService struct { client *Client retrier Retrier + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index string typ string requests []BulkableRequest @@ -37,7 +44,6 @@ type BulkService struct { refresh string routing string waitForActiveShards string - pretty bool // estimated bulk size in bytes, up to the request index sizeInBytesCursor sizeInBytes int64 @@ -52,6 +58,46 @@ func NewBulkService(client *Client) *BulkService { return builder } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *BulkService) Pretty(pretty bool) *BulkService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *BulkService) Human(human bool) *BulkService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *BulkService) ErrorTrace(errorTrace bool) *BulkService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *BulkService) FilterPath(filterPath ...string) *BulkService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *BulkService) Header(name string, value string) *BulkService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *BulkService) Headers(headers http.Header) *BulkService { + s.headers = headers + return s +} + // Reset cleans up the request queue func (s *BulkService) Reset() { s.requests = make([]BulkableRequest, 0) @@ -91,10 +137,10 @@ func (s *BulkService) Timeout(timeout string) *BulkService { // Refresh controls when changes made by this request are made visible // to search. The allowed values are: "true" (refresh the relevant // primary and replica shards immediately), "wait_for" (wait for the -// changes to be made visible by a refresh before reying), or "false" +// changes to be made visible by a refresh before replying), or "false" // (no refresh related actions). The default value is "false". // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *BulkService) Refresh(refresh string) *BulkService { s.refresh = refresh @@ -123,18 +169,10 @@ func (s *BulkService) WaitForActiveShards(waitForActiveShards string) *BulkServi return s } -// Pretty tells Elasticsearch whether to return a formatted JSON response. -func (s *BulkService) Pretty(pretty bool) *BulkService { - s.pretty = pretty - return s -} - // Add adds bulkable requests, i.e. BulkIndexRequest, BulkUpdateRequest, // and/or BulkDeleteRequest. func (s *BulkService) Add(requests ...BulkableRequest) *BulkService { - for _, r := range requests { - s.requests = append(s.requests, r) - } + s.requests = append(s.requests, requests...) return s } @@ -172,7 +210,8 @@ func (s *BulkService) NumberOfActions() int { func (s *BulkService) bodyAsString() (string, error) { // Pre-allocate to reduce allocs - buf := bytes.NewBuffer(make([]byte, 0, s.EstimatedSizeInBytes())) + var buf strings.Builder + buf.Grow(int(s.EstimatedSizeInBytes())) for _, req := range s.requests { source, err := req.Source() @@ -226,9 +265,18 @@ func (s *BulkService) Do(ctx context.Context) (*BulkResponse, error) { path += "_bulk" // Parameters - params := make(url.Values) - if s.pretty { - params.Set("pretty", fmt.Sprintf("%v", s.pretty)) + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.pipeline != "" { params.Set("pipeline", s.pipeline) @@ -254,6 +302,7 @@ func (s *BulkService) Do(ctx context.Context) (*BulkResponse, error) { Body: body, ContentType: "application/x-ndjson", Retrier: s.retrier, + Headers: s.headers, }) if err != nil { return nil, err @@ -325,7 +374,7 @@ type BulkResponseItem struct { Id string `json:"_id,omitempty"` Version int64 `json:"_version,omitempty"` Result string `json:"result,omitempty"` - Shards *shardsInfo `json:"_shards,omitempty"` + Shards *ShardsInfo `json:"_shards,omitempty"` SeqNo int64 `json:"_seq_no,omitempty"` PrimaryTerm int64 `json:"_primary_term,omitempty"` Status int `json:"status,omitempty"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request.go b/vendor/github.com/olivere/elastic/v7/bulk_delete_request.go similarity index 68% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request.go rename to vendor/github.com/olivere/elastic/v7/bulk_delete_request.go index 4bdadeb..55b2cbc 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request.go +++ b/vendor/github.com/olivere/elastic/v7/bulk_delete_request.go @@ -16,17 +16,19 @@ import ( // BulkDeleteRequest is a request to remove a document from Elasticsearch. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. type BulkDeleteRequest struct { BulkableRequest - index string - typ string - id string - parent string - routing string - version int64 // default is MATCH_ANY - versionType string // default is "internal" + index string + typ string + id string + parent string + routing string + version int64 // default is MATCH_ANY + versionType string // default is "internal" + ifSeqNo *int64 + ifPrimaryTerm *int64 source []string @@ -38,13 +40,15 @@ type bulkDeleteRequestCommand map[string]bulkDeleteRequestCommandOp //easyjson:json type bulkDeleteRequestCommandOp struct { - Index string `json:"_index,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"` + Index string `json:"_index,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"` + IfSeqNo *int64 `json:"if_seq_no,omitempty"` + IfPrimaryTerm *int64 `json:"if_primary_term,omitempty"` } // NewBulkDeleteRequest returns a new BulkDeleteRequest. @@ -116,6 +120,20 @@ func (r *BulkDeleteRequest) VersionType(versionType string) *BulkDeleteRequest { return r } +// IfSeqNo indicates to only perform the delete operation if the last +// operation that has changed the document has the specified sequence number. +func (r *BulkDeleteRequest) IfSeqNo(ifSeqNo int64) *BulkDeleteRequest { + r.ifSeqNo = &ifSeqNo + return r +} + +// IfPrimaryTerm indicates to only perform the delete operation if the +// last operation that has changed the document has the specified primary term. +func (r *BulkDeleteRequest) IfPrimaryTerm(ifPrimaryTerm int64) *BulkDeleteRequest { + r.ifPrimaryTerm = &ifPrimaryTerm + return r +} + // String returns the on-wire representation of the delete request, // concatenated as a single string. func (r *BulkDeleteRequest) String() string { @@ -128,7 +146,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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. func (r *BulkDeleteRequest) Source() ([]string, error) { if r.source != nil { @@ -136,13 +154,15 @@ func (r *BulkDeleteRequest) Source() ([]string, error) { } command := bulkDeleteRequestCommand{ "delete": bulkDeleteRequestCommandOp{ - Index: r.index, - Type: r.typ, - Id: r.id, - Routing: r.routing, - Parent: r.parent, - Version: r.version, - VersionType: r.versionType, + Index: r.index, + Type: r.typ, + Id: r.id, + Routing: r.routing, + Parent: r.parent, + Version: r.version, + VersionType: r.versionType, + IfSeqNo: r.ifSeqNo, + IfPrimaryTerm: r.ifPrimaryTerm, }, } diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request_easyjson.go b/vendor/github.com/olivere/elastic/v7/bulk_delete_request_easyjson.go similarity index 72% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request_easyjson.go rename to vendor/github.com/olivere/elastic/v7/bulk_delete_request_easyjson.go index df3452c..084e541 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_delete_request_easyjson.go +++ b/vendor/github.com/olivere/elastic/v7/bulk_delete_request_easyjson.go @@ -17,7 +17,7 @@ var ( _ easyjson.Marshaler ) -func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDeleteRequestCommandOp) { +func easyjson8092efb6DecodeGithubComOlivereElasticV7(in *jlexer.Lexer, out *bulkDeleteRequestCommandOp) { isTopLevel := in.IsStart() if in.IsNull() { if isTopLevel { @@ -50,6 +50,26 @@ func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDe out.Version = int64(in.Int64()) case "version_type": out.VersionType = string(in.String()) + case "if_seq_no": + if in.IsNull() { + in.Skip() + out.IfSeqNo = nil + } else { + if out.IfSeqNo == nil { + out.IfSeqNo = new(int64) + } + *out.IfSeqNo = int64(in.Int64()) + } + case "if_primary_term": + if in.IsNull() { + in.Skip() + out.IfPrimaryTerm = nil + } else { + if out.IfPrimaryTerm == nil { + out.IfPrimaryTerm = new(int64) + } + *out.IfPrimaryTerm = int64(in.Int64()) + } default: in.SkipRecursive() } @@ -60,18 +80,14 @@ func easyjson8092efb6DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkDe in.Consumed() } } -func easyjson8092efb6EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkDeleteRequestCommandOp) { +func easyjson8092efb6EncodeGithubComOlivereElasticV7(out *jwriter.Writer, in bulkDeleteRequestCommandOp) { out.RawByte('{') first := true _ = first if in.Index != "" { const prefix string = ",\"_index\":" - if first { - first = false - out.RawString(prefix[1:]) - } else { - out.RawString(prefix) - } + first = false + out.RawString(prefix[1:]) out.String(string(in.Index)) } if in.Type != "" { @@ -134,43 +150,59 @@ func easyjson8092efb6EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkD } out.String(string(in.VersionType)) } + if in.IfSeqNo != nil { + const prefix string = ",\"if_seq_no\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfSeqNo)) + } + if in.IfPrimaryTerm != nil { + const prefix string = ",\"if_primary_term\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfPrimaryTerm)) + } out.RawByte('}') } // MarshalJSON supports json.Marshaler interface func (v bulkDeleteRequestCommandOp) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} - easyjson8092efb6EncodeGithubComOlivereElastic(&w, v) + easyjson8092efb6EncodeGithubComOlivereElasticV7(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkDeleteRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) { - easyjson8092efb6EncodeGithubComOlivereElastic(w, v) + easyjson8092efb6EncodeGithubComOlivereElasticV7(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkDeleteRequestCommandOp) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson8092efb6DecodeGithubComOlivereElastic(&r, v) + easyjson8092efb6DecodeGithubComOlivereElasticV7(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkDeleteRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson8092efb6DecodeGithubComOlivereElastic(l, v) + easyjson8092efb6DecodeGithubComOlivereElasticV7(l, v) } -func easyjson8092efb6DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkDeleteRequestCommand) { +func easyjson8092efb6DecodeGithubComOlivereElasticV71(in *jlexer.Lexer, out *bulkDeleteRequestCommand) { isTopLevel := in.IsStart() if in.IsNull() { in.Skip() } else { in.Delim('{') - if !in.IsDelim('}') { - *out = make(bulkDeleteRequestCommand) - } else { - *out = nil - } + *out = make(bulkDeleteRequestCommand) for !in.IsDelim('}') { key := string(in.String()) in.WantColon() @@ -185,7 +217,7 @@ func easyjson8092efb6DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkD in.Consumed() } } -func easyjson8092efb6EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkDeleteRequestCommand) { +func easyjson8092efb6EncodeGithubComOlivereElasticV71(out *jwriter.Writer, in bulkDeleteRequestCommand) { if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 { out.RawString(`null`) } else { @@ -208,23 +240,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) + easyjson8092efb6EncodeGithubComOlivereElasticV71(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkDeleteRequestCommand) MarshalEasyJSON(w *jwriter.Writer) { - easyjson8092efb6EncodeGithubComOlivereElastic1(w, v) + easyjson8092efb6EncodeGithubComOlivereElasticV71(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkDeleteRequestCommand) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson8092efb6DecodeGithubComOlivereElastic1(&r, v) + easyjson8092efb6DecodeGithubComOlivereElasticV71(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkDeleteRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson8092efb6DecodeGithubComOlivereElastic1(l, v) + easyjson8092efb6DecodeGithubComOlivereElasticV71(l, v) } diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_index_request.go b/vendor/github.com/olivere/elastic/v7/bulk_index_request.go similarity index 82% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_index_request.go rename to vendor/github.com/olivere/elastic/v7/bulk_index_request.go index 0f09ac5..fcbc717 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_index_request.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. type BulkIndexRequest struct { BulkableRequest @@ -24,11 +24,13 @@ type BulkIndexRequest struct { opType string routing string parent string - version int64 // default is MATCH_ANY + version *int64 // default is MATCH_ANY versionType string // default is "internal" doc interface{} pipeline string retryOnConflict *int + ifSeqNo *int64 + ifPrimaryTerm *int64 source []string @@ -47,9 +49,11 @@ type bulkIndexRequestCommandOp struct { // 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"` + Version *int64 `json:"version,omitempty"` VersionType string `json:"version_type,omitempty"` Pipeline string `json:"pipeline,omitempty"` + IfSeqNo *int64 `json:"if_seq_no,omitempty"` + IfPrimaryTerm *int64 `json:"if_primary_term,omitempty"` } // NewBulkIndexRequest returns a new BulkIndexRequest. @@ -95,7 +99,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.2/docs-index_.html#operation-type +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-index_.html#operation-type // for details. func (r *BulkIndexRequest) OpType(opType string) *BulkIndexRequest { r.opType = opType @@ -120,7 +124,8 @@ func (r *BulkIndexRequest) Parent(parent string) *BulkIndexRequest { // Version indicates the version of the document as part of an optimistic // concurrency model. func (r *BulkIndexRequest) Version(version int64) *BulkIndexRequest { - r.version = version + v := version + r.version = &v r.source = nil return r } @@ -128,7 +133,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.2/docs-index_.html#index-versioning +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-index_.html#index-versioning // for details. func (r *BulkIndexRequest) VersionType(versionType string) *BulkIndexRequest { r.versionType = versionType @@ -157,6 +162,20 @@ func (r *BulkIndexRequest) Pipeline(pipeline string) *BulkIndexRequest { return r } +// IfSeqNo indicates to only perform the index operation if the last +// operation that has changed the document has the specified sequence number. +func (r *BulkIndexRequest) IfSeqNo(ifSeqNo int64) *BulkIndexRequest { + r.ifSeqNo = &ifSeqNo + return r +} + +// IfPrimaryTerm indicates to only perform the index operation if the +// last operation that has changed the document has the specified primary term. +func (r *BulkIndexRequest) IfPrimaryTerm(ifPrimaryTerm int64) *BulkIndexRequest { + r.ifPrimaryTerm = &ifPrimaryTerm + return r +} + // String returns the on-wire representation of the index request, // concatenated as a single string. func (r *BulkIndexRequest) String() string { @@ -169,7 +188,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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. func (r *BulkIndexRequest) Source() ([]string, error) { // { "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } } @@ -192,6 +211,8 @@ func (r *BulkIndexRequest) Source() ([]string, error) { VersionType: r.versionType, RetryOnConflict: r.retryOnConflict, Pipeline: r.pipeline, + IfSeqNo: r.ifSeqNo, + IfPrimaryTerm: r.ifPrimaryTerm, } command := bulkIndexRequestCommand{ r.opType: indexCommand, diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_index_request_easyjson.go b/vendor/github.com/olivere/elastic/v7/bulk_index_request_easyjson.go similarity index 72% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_index_request_easyjson.go rename to vendor/github.com/olivere/elastic/v7/bulk_index_request_easyjson.go index f879297..aaae24e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_index_request_easyjson.go +++ b/vendor/github.com/olivere/elastic/v7/bulk_index_request_easyjson.go @@ -17,7 +17,7 @@ var ( _ easyjson.Marshaler ) -func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIndexRequestCommandOp) { +func easyjson9de0fcbfDecodeGithubComOlivereElasticV7(in *jlexer.Lexer, out *bulkIndexRequestCommandOp) { isTopLevel := in.IsStart() if in.IsNull() { if isTopLevel { @@ -57,11 +57,39 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIn case "routing": out.Routing = string(in.String()) case "version": - out.Version = int64(in.Int64()) + if in.IsNull() { + in.Skip() + out.Version = nil + } else { + if out.Version == nil { + out.Version = new(int64) + } + *out.Version = int64(in.Int64()) + } case "version_type": out.VersionType = string(in.String()) case "pipeline": out.Pipeline = string(in.String()) + case "if_seq_no": + if in.IsNull() { + in.Skip() + out.IfSeqNo = nil + } else { + if out.IfSeqNo == nil { + out.IfSeqNo = new(int64) + } + *out.IfSeqNo = int64(in.Int64()) + } + case "if_primary_term": + if in.IsNull() { + in.Skip() + out.IfPrimaryTerm = nil + } else { + if out.IfPrimaryTerm == nil { + out.IfPrimaryTerm = new(int64) + } + *out.IfPrimaryTerm = int64(in.Int64()) + } default: in.SkipRecursive() } @@ -72,18 +100,14 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkIn in.Consumed() } } -func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkIndexRequestCommandOp) { +func easyjson9de0fcbfEncodeGithubComOlivereElasticV7(out *jwriter.Writer, in bulkIndexRequestCommandOp) { out.RawByte('{') first := true _ = first if in.Index != "" { const prefix string = ",\"_index\":" - if first { - first = false - out.RawString(prefix[1:]) - } else { - out.RawString(prefix) - } + first = false + out.RawString(prefix[1:]) out.String(string(in.Index)) } if in.Id != "" { @@ -136,7 +160,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI } out.String(string(in.Routing)) } - if in.Version != 0 { + if in.Version != nil { const prefix string = ",\"version\":" if first { first = false @@ -144,7 +168,7 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI } else { out.RawString(prefix) } - out.Int64(int64(in.Version)) + out.Int64(int64(*in.Version)) } if in.VersionType != "" { const prefix string = ",\"version_type\":" @@ -166,43 +190,59 @@ func easyjson9de0fcbfEncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkI } out.String(string(in.Pipeline)) } + if in.IfSeqNo != nil { + const prefix string = ",\"if_seq_no\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfSeqNo)) + } + if in.IfPrimaryTerm != nil { + const prefix string = ",\"if_primary_term\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfPrimaryTerm)) + } out.RawByte('}') } // MarshalJSON supports json.Marshaler interface func (v bulkIndexRequestCommandOp) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} - easyjson9de0fcbfEncodeGithubComOlivereElastic(&w, v) + easyjson9de0fcbfEncodeGithubComOlivereElasticV7(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkIndexRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) { - easyjson9de0fcbfEncodeGithubComOlivereElastic(w, v) + easyjson9de0fcbfEncodeGithubComOlivereElasticV7(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkIndexRequestCommandOp) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson9de0fcbfDecodeGithubComOlivereElastic(&r, v) + easyjson9de0fcbfDecodeGithubComOlivereElasticV7(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkIndexRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson9de0fcbfDecodeGithubComOlivereElastic(l, v) + easyjson9de0fcbfDecodeGithubComOlivereElasticV7(l, v) } -func easyjson9de0fcbfDecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkIndexRequestCommand) { +func easyjson9de0fcbfDecodeGithubComOlivereElasticV71(in *jlexer.Lexer, out *bulkIndexRequestCommand) { isTopLevel := in.IsStart() if in.IsNull() { in.Skip() } else { in.Delim('{') - if !in.IsDelim('}') { - *out = make(bulkIndexRequestCommand) - } else { - *out = nil - } + *out = make(bulkIndexRequestCommand) for !in.IsDelim('}') { key := string(in.String()) in.WantColon() @@ -217,7 +257,7 @@ func easyjson9de0fcbfDecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkI in.Consumed() } } -func easyjson9de0fcbfEncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkIndexRequestCommand) { +func easyjson9de0fcbfEncodeGithubComOlivereElasticV71(out *jwriter.Writer, in bulkIndexRequestCommand) { if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 { out.RawString(`null`) } else { @@ -240,23 +280,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) + easyjson9de0fcbfEncodeGithubComOlivereElasticV71(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkIndexRequestCommand) MarshalEasyJSON(w *jwriter.Writer) { - easyjson9de0fcbfEncodeGithubComOlivereElastic1(w, v) + easyjson9de0fcbfEncodeGithubComOlivereElasticV71(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkIndexRequestCommand) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson9de0fcbfDecodeGithubComOlivereElastic1(&r, v) + easyjson9de0fcbfDecodeGithubComOlivereElasticV71(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkIndexRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson9de0fcbfDecodeGithubComOlivereElastic1(l, v) + easyjson9de0fcbfDecodeGithubComOlivereElasticV71(l, v) } diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_processor.go b/vendor/github.com/olivere/elastic/v7/bulk_processor.go similarity index 82% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_processor.go rename to vendor/github.com/olivere/elastic/v7/bulk_processor.go index eb8620f..f2711f8 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_processor.go +++ b/vendor/github.com/olivere/elastic/v7/bulk_processor.go @@ -6,12 +6,21 @@ package elastic import ( "context" + "errors" "net" "sync" "sync/atomic" "time" ) +var ( + // ErrBulkItemRetry is returned in BulkProcessor from a worker when + // a response item needs to be retried. + ErrBulkItemRetry = errors.New("elastic: uncommitted bulk response items") + + defaultRetryItemStatusCodes = []int{408, 429, 503, 507} +) + // BulkProcessorService allows to easily process bulk requests. It allows setting // policies when to flush new bulk requests, e.g. based on a number of actions, // on the size of the actions, and/or to flush periodically. It also allows @@ -21,7 +30,9 @@ import ( // BulkProcessorService, by default, commits either every 1000 requests or when the // (estimated) size of the bulk requests exceeds 5 MB. However, it does not // commit periodically. BulkProcessorService also does retry by default, using -// an exponential backoff algorithm. +// an exponential backoff algorithm. It also will automatically re-enqueue items +// returned with a status of 408, 429, 503 or 507. You can change this +// behavior with RetryItemStatusCodes. // // The caller is responsible for setting the index and type on every // bulk request added to BulkProcessorService. @@ -30,16 +41,17 @@ import ( // Elasticsearch Java API as documented in // https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk-processor.html. type BulkProcessorService struct { - c *Client - beforeFn BulkBeforeFunc - afterFn BulkAfterFunc - name string // name of processor - numWorkers int // # of workers (>= 1) - bulkActions int // # of requests after which to commit - bulkSize int // # of bytes after which to commit - flushInterval time.Duration // periodic flush interval - wantStats bool // indicates whether to gather statistics - backoff Backoff // a custom Backoff to use for errors + c *Client + beforeFn BulkBeforeFunc + afterFn BulkAfterFunc + name string // name of processor + numWorkers int // # of workers (>= 1) + bulkActions int // # of requests after which to commit + bulkSize int // # of bytes after which to commit + flushInterval time.Duration // periodic flush interval + wantStats bool // indicates whether to gather statistics + backoff Backoff // a custom Backoff to use for errors + retryItemStatusCodes []int // array of status codes for bulk response line items that may be retried } // NewBulkProcessorService creates a new BulkProcessorService. @@ -53,6 +65,7 @@ func NewBulkProcessorService(client *Client) *BulkProcessorService { time.Duration(200)*time.Millisecond, time.Duration(10000)*time.Millisecond, ), + retryItemStatusCodes: defaultRetryItemStatusCodes, } } @@ -64,7 +77,7 @@ type BulkBeforeFunc func(executionId int64, requests []BulkableRequest) // after a commit to Elasticsearch. The err parameter signals an error. type BulkAfterFunc func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error) -// Before specifies a function to be executed before bulk requests get comitted +// Before specifies a function to be executed before bulk requests get committed // to Elasticsearch. func (s *BulkProcessorService) Before(fn BulkBeforeFunc) *BulkProcessorService { s.beforeFn = fn @@ -72,7 +85,7 @@ func (s *BulkProcessorService) Before(fn BulkBeforeFunc) *BulkProcessorService { } // After specifies a function to be executed when bulk requests have been -// comitted to Elasticsearch. The After callback executes both when the +// committed to Elasticsearch. The After callback executes both when the // commit was successful as well as on failures. func (s *BulkProcessorService) After(fn BulkAfterFunc) *BulkProcessorService { s.afterFn = fn @@ -128,6 +141,13 @@ func (s *BulkProcessorService) Backoff(backoff Backoff) *BulkProcessorService { return s } +// RetryItemStatusCodes sets an array of status codes that indicate that a bulk +// response line item should be retried. +func (s *BulkProcessorService) RetryItemStatusCodes(retryItemStatusCodes ...int) *BulkProcessorService { + s.retryItemStatusCodes = retryItemStatusCodes + return s +} + // Do creates a new BulkProcessor and starts it. // Consider the BulkProcessor as a running instance that accepts bulk requests // and commits them to Elasticsearch, spreading the work across one or more @@ -144,6 +164,12 @@ func (s *BulkProcessorService) Backoff(backoff Backoff) *BulkProcessorService { // Calling Do several times returns new BulkProcessors. You probably don't // want to do this. BulkProcessorService implements just a builder pattern. func (s *BulkProcessorService) Do(ctx context.Context) (*BulkProcessor, error) { + + retryItemStatusCodes := make(map[int]struct{}) + for _, code := range s.retryItemStatusCodes { + retryItemStatusCodes[code] = struct{}{} + } + p := newBulkProcessor( s.c, s.beforeFn, @@ -154,7 +180,8 @@ func (s *BulkProcessorService) Do(ctx context.Context) (*BulkProcessor, error) { s.bulkSize, s.flushInterval, s.wantStats, - s.backoff) + s.backoff, + retryItemStatusCodes) err := p.Start(ctx) if err != nil { @@ -228,21 +255,22 @@ func (st *BulkProcessorWorkerStats) dup() *BulkProcessorWorkerStats { // BulkProcessor is returned by setting up a BulkProcessorService and // calling the Do method. type BulkProcessor struct { - c *Client - beforeFn BulkBeforeFunc - afterFn BulkAfterFunc - name string - bulkActions int - bulkSize int - numWorkers int - executionId int64 - requestsC chan BulkableRequest - workerWg sync.WaitGroup - workers []*bulkWorker - flushInterval time.Duration - flusherStopC chan struct{} - wantStats bool - backoff Backoff + c *Client + beforeFn BulkBeforeFunc + afterFn BulkAfterFunc + name string + bulkActions int + bulkSize int + numWorkers int + executionId int64 + requestsC chan BulkableRequest + workerWg sync.WaitGroup + workers []*bulkWorker + flushInterval time.Duration + flusherStopC chan struct{} + wantStats bool + retryItemStatusCodes map[int]struct{} + backoff Backoff startedMu sync.Mutex // guards the following block started bool @@ -263,18 +291,20 @@ func newBulkProcessor( bulkSize int, flushInterval time.Duration, wantStats bool, - backoff Backoff) *BulkProcessor { + backoff Backoff, + retryItemStatusCodes map[int]struct{}) *BulkProcessor { return &BulkProcessor{ - c: client, - beforeFn: beforeFn, - afterFn: afterFn, - name: name, - numWorkers: numWorkers, - bulkActions: bulkActions, - bulkSize: bulkSize, - flushInterval: flushInterval, - wantStats: wantStats, - backoff: backoff, + c: client, + beforeFn: beforeFn, + afterFn: afterFn, + name: name, + numWorkers: numWorkers, + bulkActions: bulkActions, + bulkSize: bulkSize, + flushInterval: flushInterval, + wantStats: wantStats, + retryItemStatusCodes: retryItemStatusCodes, + backoff: backoff, } } @@ -504,13 +534,19 @@ func (w *bulkWorker) commit(ctx context.Context) error { reqs := w.service.requests res, err = w.service.Do(ctx) if err == nil { - // Check res.Items since some might be soft failures - if res.Items != nil && res.Errors { - // res.Items will be 1 to 1 with reqs in same order - for i, item := range res.Items { - for _, result := range item { - if result.Status == 429 { // too many requests - w.service.Add(reqs[i]) + // Overall bulk request was OK. But each bulk response item also has a status + if w.p.retryItemStatusCodes != nil && len(w.p.retryItemStatusCodes) > 0 { + // Check res.Items since some might be soft failures + if res.Items != nil && res.Errors { + // res.Items will be 1 to 1 with reqs in same order + for i, item := range res.Items { + for _, result := range item { + if _, found := w.p.retryItemStatusCodes[result.Status]; found { + w.service.Add(reqs[i]) + if err == nil { + err = ErrBulkItemRetry + } + } } } } @@ -574,7 +610,7 @@ func (w *bulkWorker) waitForActiveConnection(ready chan<- struct{}) { return } case <-t.C: - client.healthcheck(time.Duration(3)*time.Second, true) + client.healthcheck(context.Background(), 3*time.Second, true) if client.mustActiveConn() == nil { // found an active connection // exit and signal done to the WaitGroup diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_request.go b/vendor/github.com/olivere/elastic/v7/bulk_request.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_request.go rename to vendor/github.com/olivere/elastic/v7/bulk_request.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_update_request.go b/vendor/github.com/olivere/elastic/v7/bulk_update_request.go similarity index 82% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_update_request.go rename to vendor/github.com/olivere/elastic/v7/bulk_update_request.go index d55002a..a0ddf18 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_update_request.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. type BulkUpdateRequest struct { BulkableRequest @@ -34,6 +34,8 @@ type BulkUpdateRequest struct { detectNoop *bool doc interface{} returnSource *bool + ifSeqNo *int64 + ifPrimaryTerm *int64 source []string @@ -54,6 +56,8 @@ type bulkUpdateRequestCommandOp struct { Routing string `json:"routing,omitempty"` Version int64 `json:"version,omitempty"` VersionType string `json:"version_type,omitempty"` + IfSeqNo *int64 `json:"if_seq_no,omitempty"` + IfPrimaryTerm *int64 `json:"if_primary_term,omitempty"` } //easyjson:json @@ -120,8 +124,8 @@ func (r *BulkUpdateRequest) Parent(parent string) *BulkUpdateRequest { } // Script specifies an update script. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-bulk.html#bulk-update -// and https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html#bulk-update +// and https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details. func (r *BulkUpdateRequest) Script(script *Script) *BulkUpdateRequest { r.script = script @@ -132,7 +136,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.2/docs-update.html#_literal_scripted_upsert_literal +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update.html#_literal_scripted_upsert_literal func (r *BulkUpdateRequest) ScriptedUpsert(upsert bool) *BulkUpdateRequest { r.scriptedUpsert = &upsert r.source = nil @@ -162,6 +166,20 @@ func (r *BulkUpdateRequest) VersionType(versionType string) *BulkUpdateRequest { return r } +// IfSeqNo indicates to only perform the index operation if the last +// operation that has changed the document has the specified sequence number. +func (r *BulkUpdateRequest) IfSeqNo(ifSeqNo int64) *BulkUpdateRequest { + r.ifSeqNo = &ifSeqNo + return r +} + +// IfPrimaryTerm indicates to only perform the index operation if the +// last operation that has changed the document has the specified primary term. +func (r *BulkUpdateRequest) IfPrimaryTerm(ifPrimaryTerm int64) *BulkUpdateRequest { + r.ifPrimaryTerm = &ifPrimaryTerm + return r +} + // Doc specifies the updated document. func (r *BulkUpdateRequest) Doc(doc interface{}) *BulkUpdateRequest { r.doc = doc @@ -172,7 +190,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.2/docs-update.html#_literal_doc_as_upsert_literal +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update.html#_literal_doc_as_upsert_literal // for details. func (r *BulkUpdateRequest) DocAsUpsert(docAsUpsert bool) *BulkUpdateRequest { r.docAsUpsert = &docAsUpsert @@ -218,7 +236,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.2/docs-bulk.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-bulk.html // for details. func (r *BulkUpdateRequest) Source() ([]string, error) { // { "update" : { "_index" : "test", "_type" : "type1", "_id" : "1", ... } } @@ -243,6 +261,8 @@ func (r *BulkUpdateRequest) Source() ([]string, error) { Version: r.version, VersionType: r.versionType, RetryOnConflict: r.retryOnConflict, + IfSeqNo: r.ifSeqNo, + IfPrimaryTerm: r.ifPrimaryTerm, } command := bulkUpdateRequestCommand{ "update": updateCommand, @@ -264,12 +284,28 @@ func (r *BulkUpdateRequest) Source() ([]string, error) { lines[0] = string(body) // 2nd line: {"doc" : { ... }} or {"script": {...}} + var doc interface{} + if r.doc != nil { + // Automatically serialize strings as raw JSON + switch t := r.doc.(type) { + default: + doc = r.doc + case string: + if len(t) > 0 { + doc = json.RawMessage(t) + } + case *string: + if t != nil && len(*t) > 0 { + doc = json.RawMessage(*t) + } + } + } data := bulkUpdateRequestCommandData{ DocAsUpsert: r.docAsUpsert, DetectNoop: r.detectNoop, Upsert: r.upsert, ScriptedUpsert: r.scriptedUpsert, - Doc: r.doc, + Doc: doc, Source: r.returnSource, } if r.script != nil { diff --git a/vendor/gopkg.in/olivere/elastic.v6/bulk_update_request_easyjson.go b/vendor/github.com/olivere/elastic/v7/bulk_update_request_easyjson.go similarity index 82% rename from vendor/gopkg.in/olivere/elastic.v6/bulk_update_request_easyjson.go rename to vendor/github.com/olivere/elastic/v7/bulk_update_request_easyjson.go index d2c2cbf..79d8db1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/bulk_update_request_easyjson.go +++ b/vendor/github.com/olivere/elastic/v7/bulk_update_request_easyjson.go @@ -17,7 +17,7 @@ var ( _ easyjson.Marshaler ) -func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUpdateRequestCommandOp) { +func easyjson1ed00e60DecodeGithubComOlivereElasticV7(in *jlexer.Lexer, out *bulkUpdateRequestCommandOp) { isTopLevel := in.IsStart() if in.IsNull() { if isTopLevel { @@ -60,6 +60,26 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUp out.Version = int64(in.Int64()) case "version_type": out.VersionType = string(in.String()) + case "if_seq_no": + if in.IsNull() { + in.Skip() + out.IfSeqNo = nil + } else { + if out.IfSeqNo == nil { + out.IfSeqNo = new(int64) + } + *out.IfSeqNo = int64(in.Int64()) + } + case "if_primary_term": + if in.IsNull() { + in.Skip() + out.IfPrimaryTerm = nil + } else { + if out.IfPrimaryTerm == nil { + out.IfPrimaryTerm = new(int64) + } + *out.IfPrimaryTerm = int64(in.Int64()) + } default: in.SkipRecursive() } @@ -70,18 +90,14 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic(in *jlexer.Lexer, out *bulkUp in.Consumed() } } -func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkUpdateRequestCommandOp) { +func easyjson1ed00e60EncodeGithubComOlivereElasticV7(out *jwriter.Writer, in bulkUpdateRequestCommandOp) { out.RawByte('{') first := true _ = first if in.Index != "" { const prefix string = ",\"_index\":" - if first { - first = false - out.RawString(prefix[1:]) - } else { - out.RawString(prefix) - } + first = false + out.RawString(prefix[1:]) out.String(string(in.Index)) } if in.Type != "" { @@ -154,33 +170,53 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic(out *jwriter.Writer, in bulkU } out.String(string(in.VersionType)) } + if in.IfSeqNo != nil { + const prefix string = ",\"if_seq_no\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfSeqNo)) + } + if in.IfPrimaryTerm != nil { + const prefix string = ",\"if_primary_term\":" + if first { + first = false + out.RawString(prefix[1:]) + } else { + out.RawString(prefix) + } + out.Int64(int64(*in.IfPrimaryTerm)) + } out.RawByte('}') } // MarshalJSON supports json.Marshaler interface func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} - easyjson1ed00e60EncodeGithubComOlivereElastic(&w, v) + easyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkUpdateRequestCommandOp) MarshalEasyJSON(w *jwriter.Writer) { - easyjson1ed00e60EncodeGithubComOlivereElastic(w, v) + easyjson1ed00e60EncodeGithubComOlivereElasticV7(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson1ed00e60DecodeGithubComOlivereElastic(&r, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkUpdateRequestCommandOp) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson1ed00e60DecodeGithubComOlivereElastic(l, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV7(l, v) } -func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkUpdateRequestCommandData) { +func easyjson1ed00e60DecodeGithubComOlivereElasticV71(in *jlexer.Lexer, out *bulkUpdateRequestCommandData) { isTopLevel := in.IsStart() if in.IsNull() { if isTopLevel { @@ -273,18 +309,14 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic1(in *jlexer.Lexer, out *bulkU in.Consumed() } } -func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulkUpdateRequestCommandData) { +func easyjson1ed00e60EncodeGithubComOlivereElasticV71(out *jwriter.Writer, in bulkUpdateRequestCommandData) { out.RawByte('{') first := true _ = first if in.DetectNoop != nil { const prefix string = ",\"detect_noop\":" - if first { - first = false - out.RawString(prefix[1:]) - } else { - out.RawString(prefix) - } + first = false + out.RawString(prefix[1:]) out.Bool(bool(*in.DetectNoop)) } if in.Doc != nil { @@ -371,37 +403,33 @@ func easyjson1ed00e60EncodeGithubComOlivereElastic1(out *jwriter.Writer, in bulk // MarshalJSON supports json.Marshaler interface func (v bulkUpdateRequestCommandData) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} - easyjson1ed00e60EncodeGithubComOlivereElastic1(&w, v) + easyjson1ed00e60EncodeGithubComOlivereElasticV71(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkUpdateRequestCommandData) MarshalEasyJSON(w *jwriter.Writer) { - easyjson1ed00e60EncodeGithubComOlivereElastic1(w, v) + easyjson1ed00e60EncodeGithubComOlivereElasticV71(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson1ed00e60DecodeGithubComOlivereElastic1(&r, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkUpdateRequestCommandData) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson1ed00e60DecodeGithubComOlivereElastic1(l, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV71(l, v) } -func easyjson1ed00e60DecodeGithubComOlivereElastic2(in *jlexer.Lexer, out *bulkUpdateRequestCommand) { +func easyjson1ed00e60DecodeGithubComOlivereElasticV72(in *jlexer.Lexer, out *bulkUpdateRequestCommand) { isTopLevel := in.IsStart() if in.IsNull() { in.Skip() } else { in.Delim('{') - if !in.IsDelim('}') { - *out = make(bulkUpdateRequestCommand) - } else { - *out = nil - } + *out = make(bulkUpdateRequestCommand) for !in.IsDelim('}') { key := string(in.String()) in.WantColon() @@ -416,7 +444,7 @@ func easyjson1ed00e60DecodeGithubComOlivereElastic2(in *jlexer.Lexer, out *bulkU in.Consumed() } } -func easyjson1ed00e60EncodeGithubComOlivereElastic2(out *jwriter.Writer, in bulkUpdateRequestCommand) { +func easyjson1ed00e60EncodeGithubComOlivereElasticV72(out *jwriter.Writer, in bulkUpdateRequestCommand) { if in == nil && (out.Flags&jwriter.NilMapAsEmpty) == 0 { out.RawString(`null`) } else { @@ -439,23 +467,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) + easyjson1ed00e60EncodeGithubComOlivereElasticV72(&w, v) return w.Buffer.BuildBytes(), w.Error } // MarshalEasyJSON supports easyjson.Marshaler interface func (v bulkUpdateRequestCommand) MarshalEasyJSON(w *jwriter.Writer) { - easyjson1ed00e60EncodeGithubComOlivereElastic2(w, v) + easyjson1ed00e60EncodeGithubComOlivereElasticV72(w, v) } // UnmarshalJSON supports json.Unmarshaler interface func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} - easyjson1ed00e60DecodeGithubComOlivereElastic2(&r, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v) return r.Error() } // UnmarshalEasyJSON supports easyjson.Unmarshaler interface func (v *bulkUpdateRequestCommand) UnmarshalEasyJSON(l *jlexer.Lexer) { - easyjson1ed00e60DecodeGithubComOlivereElastic2(l, v) + easyjson1ed00e60DecodeGithubComOlivereElasticV72(l, v) } diff --git a/vendor/gopkg.in/olivere/elastic.v6/canonicalize.go b/vendor/github.com/olivere/elastic/v7/canonicalize.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/canonicalize.go rename to vendor/github.com/olivere/elastic/v7/canonicalize.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/cat_aliases.go b/vendor/github.com/olivere/elastic/v7/cat_aliases.go similarity index 65% rename from vendor/gopkg.in/olivere/elastic.v6/cat_aliases.go rename to vendor/github.com/olivere/elastic/v7/cat_aliases.go index 4e49ce8..ddadef5 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cat_aliases.go +++ b/vendor/github.com/olivere/elastic/v7/cat_aliases.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // CatAliasesService shows information about currently configured aliases // to indices including filter and routing infos. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cat-aliases.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cat-aliases.html // for details. type CatAliasesService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + local *bool masterTimeout string aliases []string @@ -35,6 +42,46 @@ func NewCatAliasesService(client *Client) *CatAliasesService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatAliasesService) Pretty(pretty bool) *CatAliasesService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatAliasesService) Human(human bool) *CatAliasesService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatAliasesService) ErrorTrace(errorTrace bool) *CatAliasesService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatAliasesService) FilterPath(filterPath ...string) *CatAliasesService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatAliasesService) Header(name string, value string) *CatAliasesService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatAliasesService) Headers(headers http.Header) *CatAliasesService { + s.headers = headers + return s +} + // Alias specifies one or more aliases to which information should be returned. func (s *CatAliasesService) Alias(alias ...string) *CatAliasesService { s.aliases = alias @@ -74,12 +121,6 @@ func (s *CatAliasesService) Sort(fields ...string) *CatAliasesService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CatAliasesService) Pretty(pretty bool) *CatAliasesService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *CatAliasesService) buildURL() (string, url.Values, error) { // Build URL @@ -103,8 +144,17 @@ func (s *CatAliasesService) buildURL() (string, url.Values, error) { params := url.Values{ "format": []string{"json"}, // always returns as JSON } - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if v := s.local; v != nil { params.Set("local", fmt.Sprint(*v)) @@ -115,6 +165,9 @@ func (s *CatAliasesService) buildURL() (string, url.Values, error) { if len(s.sort) > 0 { params.Set("s", strings.Join(s.sort, ",")) } + if len(s.columns) > 0 { + params.Set("h", strings.Join(s.columns, ",")) + } return path, params, nil } @@ -128,9 +181,10 @@ func (s *CatAliasesService) Do(ctx context.Context) (CatAliasesResponse, error) // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -163,4 +217,6 @@ type CatAliasesResponseRow struct { RoutingIndex string `json:"routing.index"` // RoutingSearch specifies the search routing (or "-"). RoutingSearch string `json:"routing.search"` + // IsWriteIndex indicates whether the index can be written to (or "-"). + IsWriteIndex string `json:"is_write_index"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/cat_allocation.go b/vendor/github.com/olivere/elastic/v7/cat_allocation.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/cat_allocation.go rename to vendor/github.com/olivere/elastic/v7/cat_allocation.go index ec15dca..0e49707 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cat_allocation.go +++ b/vendor/github.com/olivere/elastic/v7/cat_allocation.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // CatAllocationService provides a snapshot of how many shards are allocated // to each data node and how much disk space they are using. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cat-allocation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cat-allocation.html // for details. type CatAllocationService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + bytes string // b, k, m, or g local *bool masterTimeout string @@ -36,6 +43,46 @@ func NewCatAllocationService(client *Client) *CatAllocationService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatAllocationService) Pretty(pretty bool) *CatAllocationService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatAllocationService) Human(human bool) *CatAllocationService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatAllocationService) ErrorTrace(errorTrace bool) *CatAllocationService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatAllocationService) FilterPath(filterPath ...string) *CatAllocationService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatAllocationService) Header(name string, value string) *CatAllocationService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatAllocationService) Headers(headers http.Header) *CatAllocationService { + s.headers = headers + return s +} + // NodeID specifies one or more node IDs to for information should be returned. func (s *CatAllocationService) NodeID(nodes ...string) *CatAllocationService { s.nodes = nodes @@ -82,12 +129,6 @@ func (s *CatAllocationService) Sort(fields ...string) *CatAllocationService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CatAllocationService) Pretty(pretty bool) *CatAllocationService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *CatAllocationService) buildURL() (string, url.Values, error) { // Build URL @@ -111,8 +152,17 @@ func (s *CatAllocationService) buildURL() (string, url.Values, error) { params := url.Values{ "format": []string{"json"}, // always returns as JSON } - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.bytes != "" { params.Set("bytes", s.bytes) @@ -126,6 +176,9 @@ func (s *CatAllocationService) buildURL() (string, url.Values, error) { if len(s.sort) > 0 { params.Set("s", strings.Join(s.sort, ",")) } + if len(s.columns) > 0 { + params.Set("h", strings.Join(s.columns, ",")) + } return path, params, nil } @@ -139,9 +192,10 @@ func (s *CatAllocationService) Do(ctx context.Context) (CatAllocationResponse, e // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/cat_count.go b/vendor/github.com/olivere/elastic/v7/cat_count.go similarity index 65% rename from vendor/gopkg.in/olivere/elastic.v6/cat_count.go rename to vendor/github.com/olivere/elastic/v7/cat_count.go index 87d67c8..82fffd9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cat_count.go +++ b/vendor/github.com/olivere/elastic/v7/cat_count.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // CatCountService provides quick access to the document count of the entire cluster, // or individual indices. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cat-count.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cat-count.html // for details. type CatCountService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string local *bool masterTimeout string @@ -35,6 +42,46 @@ func NewCatCountService(client *Client) *CatCountService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatCountService) Pretty(pretty bool) *CatCountService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatCountService) Human(human bool) *CatCountService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatCountService) ErrorTrace(errorTrace bool) *CatCountService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatCountService) FilterPath(filterPath ...string) *CatCountService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatCountService) Header(name string, value string) *CatCountService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatCountService) Headers(headers http.Header) *CatCountService { + s.headers = headers + return s +} + // Index specifies zero or more indices for which to return counts // (by default counts for all indices are returned). func (s *CatCountService) Index(index ...string) *CatCountService { @@ -75,12 +122,6 @@ func (s *CatCountService) Sort(fields ...string) *CatCountService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CatCountService) Pretty(pretty bool) *CatCountService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *CatCountService) buildURL() (string, url.Values, error) { // Build URL @@ -104,8 +145,17 @@ func (s *CatCountService) buildURL() (string, url.Values, error) { params := url.Values{ "format": []string{"json"}, // always returns as JSON } - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if v := s.local; v != nil { params.Set("local", fmt.Sprint(*v)) @@ -116,6 +166,9 @@ func (s *CatCountService) buildURL() (string, url.Values, error) { if len(s.sort) > 0 { params.Set("s", strings.Join(s.sort, ",")) } + if len(s.columns) > 0 { + params.Set("h", strings.Join(s.columns, ",")) + } return path, params, nil } @@ -129,9 +182,10 @@ func (s *CatCountService) Do(ctx context.Context) (CatCountResponse, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/cat_health.go b/vendor/github.com/olivere/elastic/v7/cat_health.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/cat_health.go rename to vendor/github.com/olivere/elastic/v7/cat_health.go index 55dd79b..2d6bf89 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cat_health.go +++ b/vendor/github.com/olivere/elastic/v7/cat_health.go @@ -7,6 +7,7 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" ) @@ -14,11 +15,17 @@ import ( // CatHealthService returns a terse representation of the same information // as /_cluster/health. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cat-health.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cat-health.html // for details. type CatHealthService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + local *bool masterTimeout string columns []string @@ -33,6 +40,46 @@ func NewCatHealthService(client *Client) *CatHealthService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatHealthService) Pretty(pretty bool) *CatHealthService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatHealthService) Human(human bool) *CatHealthService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatHealthService) ErrorTrace(errorTrace bool) *CatHealthService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatHealthService) FilterPath(filterPath ...string) *CatHealthService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatHealthService) Header(name string, value string) *CatHealthService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatHealthService) Headers(headers http.Header) *CatHealthService { + s.headers = headers + return s +} + // Local indicates to return local information, i.e. do not retrieve // the state from master node (default: false). func (s *CatHealthService) Local(local bool) *CatHealthService { @@ -72,12 +119,6 @@ func (s *CatHealthService) DisableTimestamping(disable bool) *CatHealthService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CatHealthService) Pretty(pretty bool) *CatHealthService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *CatHealthService) buildURL() (string, url.Values, error) { // Build URL @@ -87,8 +128,17 @@ func (s *CatHealthService) buildURL() (string, url.Values, error) { params := url.Values{ "format": []string{"json"}, // always returns as JSON } - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if v := s.local; v != nil { params.Set("local", fmt.Sprint(*v)) @@ -102,6 +152,9 @@ func (s *CatHealthService) buildURL() (string, url.Values, error) { if v := s.disableTimestamping; v != nil { params.Set("ts", fmt.Sprint(*v)) } + if len(s.columns) > 0 { + params.Set("h", strings.Join(s.columns, ",")) + } return path, params, nil } @@ -115,9 +168,10 @@ func (s *CatHealthService) Do(ctx context.Context) (CatHealthResponse, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/cat_indices.go b/vendor/github.com/olivere/elastic/v7/cat_indices.go similarity index 65% rename from vendor/gopkg.in/olivere/elastic.v6/cat_indices.go rename to vendor/github.com/olivere/elastic/v7/cat_indices.go index 70eb08a..77725c1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cat_indices.go +++ b/vendor/github.com/olivere/elastic/v7/cat_indices.go @@ -7,20 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // CatIndicesService returns the list of indices plus some additional // information about them. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cat-indices.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cat-indices.html // for details. type CatIndicesService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + index string bytes string // b, k, m, or g local *bool @@ -29,6 +35,7 @@ type CatIndicesService struct { health string // green, yellow, or red primaryOnly *bool // true for primary shards only sort []string // list of columns for sort order + headers http.Header } // NewCatIndicesService creates a new CatIndicesService. @@ -38,6 +45,46 @@ func NewCatIndicesService(client *Client) *CatIndicesService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatIndicesService) Pretty(pretty bool) *CatIndicesService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatIndicesService) Human(human bool) *CatIndicesService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatIndicesService) ErrorTrace(errorTrace bool) *CatIndicesService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatIndicesService) FilterPath(filterPath ...string) *CatIndicesService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatIndicesService) Header(name string, value string) *CatIndicesService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatIndicesService) Headers(headers http.Header) *CatIndicesService { + s.headers = headers + return s +} + // Index is the name of the index to list (by default all indices are returned). func (s *CatIndicesService) Index(index string) *CatIndicesService { s.index = index @@ -97,12 +144,6 @@ func (s *CatIndicesService) Sort(fields ...string) *CatIndicesService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CatIndicesService) Pretty(pretty bool) *CatIndicesService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *CatIndicesService) buildURL() (string, url.Values, error) { // Build URL @@ -126,8 +167,17 @@ func (s *CatIndicesService) buildURL() (string, url.Values, error) { params := url.Values{ "format": []string{"json"}, // always returns as JSON } - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.bytes != "" { params.Set("bytes", s.bytes) @@ -138,6 +188,25 @@ func (s *CatIndicesService) buildURL() (string, url.Values, error) { if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) } + if len(s.columns) > 0 { + // loop through all columns and apply alias if needed + for i, column := range s.columns { + if fullValueRaw, isAliased := catIndicesResponseRowAliasesMap[column]; isAliased { + // alias can be translated to multiple fields, + // so if translated value contains a comma, than replace the first value + // and append the others + if strings.Contains(fullValueRaw, ",") { + fullValues := strings.Split(fullValueRaw, ",") + s.columns[i] = fullValues[0] + s.columns = append(s.columns, fullValues[1:]...) + } else { + s.columns[i] = fullValueRaw + } + } + } + + params.Set("h", strings.Join(s.columns, ",")) + } if s.health != "" { params.Set("health", s.health) } @@ -160,9 +229,10 @@ func (s *CatIndicesService) Do(ctx context.Context) (CatIndicesResponse, error) // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -216,8 +286,8 @@ type CatIndicesResponseRow struct { PriRequestCacheHitCount int `json:"pri.request_cache.hit_count,string"` // request cache hit count on primaries RequestCacheMissCount int `json:"request_cache.miss_count,string"` // request cache miss count on primaries & replicas PriRequestCacheMissCount int `json:"pri.request_cache.miss_count,string"` // request cache miss count on primaries - FlushTotal int `json:"flush.total"` // number of flushes on primaries & replicas - PriFlushTotal int `json:"pri.flush.total"` // number of flushes on primaries + FlushTotal int `json:"flush.total,string"` // number of flushes on primaries & replicas + PriFlushTotal int `json:"pri.flush.total,string"` // number of flushes on primaries FlushTotalTime string `json:"flush.total_time"` // time spent in flush on primaries & replicas PriFlushTotalTime string `json:"pri.flush.total_time"` // time spent in flush on primaries GetCurrent int `json:"get.current,string"` // number of current get ops on primaries & replicas @@ -264,8 +334,12 @@ type CatIndicesResponseRow struct { PriMergesTotalTime string `json:"pri.merges.total_time"` // time spent in merges on primaries RefreshTotal int `json:"refresh.total,string"` // total refreshes on primaries & replicas PriRefreshTotal int `json:"pri.refresh.total,string"` // total refreshes on primaries + RefreshExternalTotal int `json:"refresh.external_total,string"` // total external refreshes on primaries & replicas + PriRefreshExternalTotal int `json:"pri.refresh.external_total,string"` // total external refreshes on primaries RefreshTime string `json:"refresh.time"` // time spent in refreshes on primaries & replicas PriRefreshTime string `json:"pri.refresh.time"` // time spent in refreshes on primaries + RefreshExternalTime string `json:"refresh.external_time"` // external time spent in refreshes on primaries & replicas + PriRefreshExternalTime string `json:"pri.refresh.external_time"` // external time spent in refreshes on primaries RefreshListeners int `json:"refresh.listeners,string"` // number of pending refresh listeners on primaries & replicas PriRefreshListeners int `json:"pri.refresh.listeners,string"` // number of pending refresh listeners on primaries SearchFetchCurrent int `json:"search.fetch_current,string"` // current fetch phase ops on primaries & replicas @@ -288,6 +362,7 @@ type CatIndicesResponseRow struct { PriSearchScrollTime string `json:"pri.search.scroll_time"` // time scroll contexts held open on primaries, e.g. "0s" SearchScrollTotal int `json:"search.scroll_total,string"` // completed scroll contexts on primaries & replicas PriSearchScrollTotal int `json:"pri.search.scroll_total,string"` // completed scroll contexts on primaries + SearchThrottled bool `json:"search.throttled,string"` // indicates if the index is search throttled SegmentsCount int `json:"segments.count,string"` // number of segments on primaries & replicas PriSegmentsCount int `json:"pri.segments.count,string"` // number of segments on primaries SegmentsMemory string `json:"segments.memory"` // memory used by segments on primaries & replicas, e.g. "1.3kb" @@ -298,8 +373,8 @@ type CatIndicesResponseRow struct { PriSegmentsVersionMapMemory string `json:"pri.segments.version_map_memory"` // memory used by version map on primaries, e.g. "0b" SegmentsFixedBitsetMemory string `json:"segments.fixed_bitset_memory"` // memory used by fixed bit sets for nested object field types and type filters for types referred in _parent fields on primaries & replicas, e.g. "0b" PriSegmentsFixedBitsetMemory string `json:"pri.segments.fixed_bitset_memory"` // memory used by fixed bit sets for nested object field types and type filters for types referred in _parent fields on primaries, e.g. "0b" - WarmerCurrent int `json:"warmer.count,string"` // current warmer ops on primaries & replicas - PriWarmerCurrent int `json:"pri.warmer.count,string"` // current warmer ops on primaries + WarmerCurrent int `json:"warmer.current,string"` // current warmer ops on primaries & replicas + PriWarmerCurrent int `json:"pri.warmer.current,string"` // current warmer ops on primaries WarmerTotal int `json:"warmer.total,string"` // total warmer ops on primaries & replicas PriWarmerTotal int `json:"pri.warmer.total,string"` // total warmer ops on primaries WarmerTotalTime string `json:"warmer.total_time"` // time spent in warmers on primaries & replicas, e.g. "47s" @@ -313,3 +388,144 @@ type CatIndicesResponseRow struct { MemoryTotal string `json:"memory.total"` // total user memory on primaries & replicas, e.g. "1.5kb" PriMemoryTotal string `json:"pri.memory.total"` // total user memory on primaries, e.g. "1.5kb" } + +// catIndicesResponseRowAliasesMap holds the global map for columns aliases +// the map is used by CatIndicesService.buildURL +// for backwards compatibility some fields are able to have the same aliases +// that means that one alias can be translated to different columns (from different elastic versions) +// example for understanding: rto -> RefreshTotal, RefreshExternalTotal +var catIndicesResponseRowAliasesMap = map[string]string{ + "qce": "query_cache.evictions", + "searchFetchTime": "search.fetch_time", + "memoryTotal": "memory.total", + "requestCacheEvictions": "request_cache.evictions", + "ftt": "flush.total_time", + "iic": "indexing.index_current", + "mtt": "merges.total_time", + "scti": "search.scroll_time", + "searchScrollTime": "search.scroll_time", + "segmentsCount": "segments.count", + "getTotal": "get.total", + "sfti": "search.fetch_time", + "searchScrollCurrent": "search.scroll_current", + "svmm": "segments.version_map_memory", + "warmerTotalTime": "warmer.total_time", + "r": "rep", + "indexingIndexTime": "indexing.index_time", + "refreshTotal": "refresh.total,refresh.external_total", + "scc": "search.scroll_current", + "suggestTime": "suggest.time", + "idc": "indexing.delete_current", + "rti": "refresh.time,refresh.external_time", + "sfto": "search.fetch_total", + "completionSize": "completion.size", + "mt": "merges.total", + "segmentsVersionMapMemory": "segments.version_map_memory", + "rto": "refresh.total,refresh.external_total", + "id": "uuid", + "dd": "docs.deleted", + "docsDeleted": "docs.deleted", + "fielddataMemory": "fielddata.memory_size", + "getTime": "get.time", + "getExistsTime": "get.exists_time", + "mtd": "merges.total_docs", + "rli": "refresh.listeners", + "h": "health", + "cds": "creation.date.string", + "rcmc": "request_cache.miss_count", + "iif": "indexing.index_failed", + "warmerCurrent": "warmer.current", + "gti": "get.time", + "indexingIndexFailed": "indexing.index_failed", + "mts": "merges.total_size", + "sqti": "search.query_time", + "segmentsIndexWriterMemory": "segments.index_writer_memory", + "iiti": "indexing.index_time", + "iito": "indexing.index_total", + "cd": "creation.date", + "gc": "get.current", + "searchFetchTotal": "search.fetch_total", + "sqc": "search.query_current", + "segmentsMemory": "segments.memory", + "dc": "docs.count", + "qcm": "query_cache.memory_size", + "queryCacheMemory": "query_cache.memory_size", + "mergesTotalDocs": "merges.total_docs", + "searchOpenContexts": "search.open_contexts", + "shards.primary": "pri", + "cs": "completion.size", + "mergesTotalTIme": "merges.total_time", + "wtt": "warmer.total_time", + "mergesCurrentSize": "merges.current_size", + "mergesTotal": "merges.total", + "refreshTime": "refresh.time,refresh.external_time", + "wc": "warmer.current", + "p": "pri", + "idti": "indexing.delete_time", + "searchQueryCurrent": "search.query_current", + "warmerTotal": "warmer.total", + "suggestTotal": "suggest.total", + "tm": "memory.total", + "ss": "store.size", + "ft": "flush.total", + "getExistsTotal": "get.exists_total", + "scto": "search.scroll_total", + "s": "status", + "queryCacheEvictions": "query_cache.evictions", + "rce": "request_cache.evictions", + "geto": "get.exists_total", + "refreshListeners": "refresh.listeners", + "suto": "suggest.total", + "storeSize": "store.size", + "gmti": "get.missing_time", + "indexingIdexCurrent": "indexing.index_current", + "searchFetchCurrent": "search.fetch_current", + "idx": "index", + "fm": "fielddata.memory_size", + "geti": "get.exists_time", + "indexingDeleteCurrent": "indexing.delete_current", + "mergesCurrentDocs": "merges.current_docs", + "sth": "search.throttled", + "flushTotal": "flush.total", + "sfc": "search.fetch_current", + "wto": "warmer.total", + "suti": "suggest.time", + "shardsReplica": "rep", + "mergesCurrent": "merges.current", + "mcs": "merges.current_size", + "so": "search.open_contexts", + "i": "index", + "siwm": "segments.index_writer_memory", + "sfbm": "segments.fixed_bitset_memory", + "fe": "fielddata.evictions", + "requestCacheMissCount": "request_cache.miss_count", + "idto": "indexing.delete_total", + "mergesTotalSize": "merges.total_size", + "suc": "suggest.current", + "suggestCurrent": "suggest.current", + "flushTotalTime": "flush.total_time", + "getMissingTotal": "get.missing_total", + "sqto": "search.query_total", + "searchScrollTotal": "search.scroll_total", + "fixedBitsetMemory": "segments.fixed_bitset_memory", + "getMissingTime": "get.missing_time", + "indexingDeleteTotal": "indexing.delete_total", + "mcd": "merges.current_docs", + "docsCount": "docs.count", + "gto": "get.total", + "mc": "merges.current", + "fielddataEvictions": "fielddata.evictions", + "rcm": "request_cache.memory_size", + "requestCacheHitCount": "request_cache.hit_count", + "gmto": "get.missing_total", + "searchQueryTime": "search.query_time", + "shards.replica": "rep", + "requestCacheMemory": "request_cache.memory_size", + "rchc": "request_cache.hit_count", + "getCurrent": "get.current", + "indexingIndexTotal": "indexing.index_total", + "sc": "segments.count,segments.memory", + "shardsPrimary": "pri", + "indexingDeleteTime": "indexing.delete_time", + "searchQueryTotal": "search.query_total", +} diff --git a/vendor/github.com/olivere/elastic/v7/cat_shards.go b/vendor/github.com/olivere/elastic/v7/cat_shards.go new file mode 100644 index 0000000..c2ccfc5 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/cat_shards.go @@ -0,0 +1,387 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// CatShardsService returns the list of shards plus some additional +// information about them. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.6/cat-shards.html +// for details. +type CatShardsService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + + index []string + bytes string // b, k, kb, m, mb, g, gb, t, tb, p, or pb + local *bool + masterTimeout string + columns []string + time string // d, h, m, s, ms, micros, or nanos + sort []string // list of columns for sort order + headers http.Header +} + +// NewCatShardsService creates a new CatShardsService. +func NewCatShardsService(client *Client) *CatShardsService { + return &CatShardsService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CatShardsService) Pretty(pretty bool) *CatShardsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CatShardsService) Human(human bool) *CatShardsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CatShardsService) ErrorTrace(errorTrace bool) *CatShardsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CatShardsService) FilterPath(filterPath ...string) *CatShardsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CatShardsService) Header(name string, value string) *CatShardsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CatShardsService) Headers(headers http.Header) *CatShardsService { + s.headers = headers + return s +} + +// Index is the name of the index to list (by default all indices are returned). +func (s *CatShardsService) Index(index ...string) *CatShardsService { + s.index = index + return s +} + +// Bytes represents the unit in which to display byte values. +// Valid values are: "b", "k", "kb", "m", "mb", "g", "gb", "t", "tb", "p" or "pb". +func (s *CatShardsService) Bytes(bytes string) *CatShardsService { + s.bytes = bytes + return s +} + +// Local indicates to return local information, i.e. do not retrieve +// the state from master node (default: false). +func (s *CatShardsService) Local(local bool) *CatShardsService { + s.local = &local + return s +} + +// MasterTimeout is the explicit operation timeout for connection to master node. +func (s *CatShardsService) MasterTimeout(masterTimeout string) *CatShardsService { + s.masterTimeout = masterTimeout + return s +} + +// Columns to return in the response. +// +// To get a list of all possible columns to return, run the following command +// in your terminal: +// +// Example: +// curl 'http://localhost:9200/_cat/shards?help' +// +// You can use Columns("*") to return all possible columns. That might take +// a little longer than the default set of columns. +func (s *CatShardsService) Columns(columns ...string) *CatShardsService { + s.columns = columns + return s +} + +// Sort is a list of fields to sort by. +func (s *CatShardsService) Sort(fields ...string) *CatShardsService { + s.sort = fields + return s +} + +// Time specifies the way that time values are formatted with. +func (s *CatShardsService) Time(time string) *CatShardsService { + s.time = time + return s +} + +// buildURL builds the URL for the operation. +func (s *CatShardsService) buildURL() (string, url.Values, error) { + // Build URL + var ( + path string + err error + ) + + if len(s.index) > 0 { + path, err = uritemplates.Expand("/_cat/shards/{index}", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else { + path = "/_cat/shards" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{ + "format": []string{"json"}, // always returns as JSON + } + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.bytes != "" { + params.Set("bytes", s.bytes) + } + if s.time != "" { + params.Set("time", s.time) + } + if v := s.local; v != nil { + params.Set("local", fmt.Sprint(*v)) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if len(s.columns) > 0 { + // loop through all columns and apply alias if needed + for i, column := range s.columns { + if fullValueRaw, isAliased := catShardsResponseRowAliasesMap[column]; isAliased { + // alias can be translated to multiple fields, + // so if translated value contains a comma, than replace the first value + // and append the others + if strings.Contains(fullValueRaw, ",") { + fullValues := strings.Split(fullValueRaw, ",") + s.columns[i] = fullValues[0] + s.columns = append(s.columns, fullValues[1:]...) + } else { + s.columns[i] = fullValueRaw + } + } + } + params.Set("h", strings.Join(s.columns, ",")) + } + if len(s.sort) > 0 { + params.Set("s", strings.Join(s.sort, ",")) + } + return path, params, nil +} + +// Do executes the operation. +func (s *CatShardsService) Do(ctx context.Context) (CatShardsResponse, error) { + // Get URL for request + path, params, err := s.buildURL() + if err != nil { + return nil, err + } + + // Get HTTP response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + var ret CatShardsResponse + if err := s.client.decoder.Decode(res.Body, &ret); err != nil { + return nil, err + } + return ret, nil +} + +// -- Result of a get request. + +// CatShardsResponse is the outcome of CatShardsService.Do. +type CatShardsResponse []CatShardsResponseRow + +// CatShardsResponseRow specifies the data returned for one index +// of a CatShardsResponse. Notice that not all of these fields might +// be filled; that depends on the number of columns chose in the +// request (see CatShardsService.Columns). +type CatShardsResponseRow struct { + Index string `json:"index"` // index name + UUID string `json:"uuid"` // index uuid + Shard int `json:"shard,string"` // shard number, e.g. 1 + Prirep string `json:"prirep"` // "r" for replica, "p" for primary + State string `json:"state"` // STARTED, INITIALIZING, RELOCATING, or UNASSIGNED + Docs int64 `json:"docs,string"` // number of documents, e.g. 142847 + Store string `json:"store"` // size, e.g. "40mb" + IP string `json:"ip"` // IP address + ID string `json:"id"` + Node string `json:"node"` // Node name + SyncID string `json:"sync_id"` + UnassignedReason string `json:"unassigned.reason"` + UnassignedAt string `json:"unassigned.at"` + UnassignedFor string `json:"unassigned.for"` + UnassignedDetails string `json:"unassigned.details"` + RecoverysourceType string `json:"recoverysource.type"` + CompletionSize string `json:"completion.size"` // size of completion on primaries & replicas + FielddataMemorySize string `json:"fielddata.memory_size"` // used fielddata cache on primaries & replicas + FielddataEvictions int `json:"fielddata.evictions,string"` // fielddata evictions on primaries & replicas + QueryCacheMemorySize string `json:"query_cache.memory_size"` // used query cache on primaries & replicas + QueryCacheEvictions int `json:"query_cache.evictions,string"` // query cache evictions on primaries & replicas + FlushTotal int `json:"flush.total,string"` // number of flushes on primaries & replicas + FlushTotalTime string `json:"flush.total_time"` // time spent in flush on primaries & replicas + GetCurrent int `json:"get.current,string"` // number of current get ops on primaries & replicas + GetTime string `json:"get.time"` // time spent in get on primaries & replicas + GetTotal int `json:"get.total,string"` // number of get ops on primaries & replicas + GetExistsTime string `json:"get.exists_time"` // time spent in successful gets on primaries & replicas + GetExistsTotal int `json:"get.exists_total,string"` // number of successful gets on primaries & replicas + GetMissingTime string `json:"get.missing_time"` // time spent in failed gets on primaries & replicas + GetMissingTotal int `json:"get.missing_total,string"` // number of failed gets on primaries & replicas + IndexingDeleteCurrent int `json:"indexing.delete_current,string"` // number of current deletions on primaries & replicas + IndexingDeleteTime string `json:"indexing.delete_time"` // time spent in deletions on primaries & replicas + IndexingDeleteTotal int `json:"indexing.delete_total,string"` // number of delete ops on primaries & replicas + IndexingIndexCurrent int `json:"indexing.index_current,string"` // number of current indexing on primaries & replicas + IndexingIndexTime string `json:"indexing.index_time"` // time spent in indexing on primaries & replicas + IndexingIndexTotal int `json:"indexing.index_total,string"` // number of index ops on primaries & replicas + IndexingIndexFailed int `json:"indexing.index_failed,string"` // number of failed indexing ops on primaries & replicas + MergesCurrent int `json:"merges.current,string"` // number of current merges on primaries & replicas + MergesCurrentDocs int `json:"merges.current_docs,string"` // number of current merging docs on primaries & replicas + MergesCurrentSize string `json:"merges.current_size"` // size of current merges on primaries & replicas + MergesTotal int `json:"merges.total,string"` // number of completed merge ops on primaries & replicas + MergesTotalDocs int `json:"merges.total_docs,string"` // docs merged on primaries & replicas + MergesTotalSize string `json:"merges.total_size"` // size merged on primaries & replicas + MergesTotalTime string `json:"merges.total_time"` // time spent in merges on primaries & replicas + RefreshTotal int `json:"refresh.total,string"` // total refreshes on primaries & replicas + RefreshExternalTotal int `json:"refresh.external_total,string"` // total external refreshes on primaries & replicas + RefreshTime string `json:"refresh.time"` // time spent in refreshes on primaries & replicas + RefreshExternalTime string `json:"refresh.external_time"` // external time spent in refreshes on primaries & replicas + RefreshListeners int `json:"refresh.listeners,string"` // number of pending refresh listeners on primaries & replicas + SearchFetchCurrent int `json:"search.fetch_current,string"` // current fetch phase ops on primaries & replicas + SearchFetchTime string `json:"search.fetch_time"` // time spent in fetch phase on primaries & replicas + SearchFetchTotal int `json:"search.fetch_total,string"` // total fetch ops on primaries & replicas + SearchOpenContexts int `json:"search.open_contexts,string"` // open search contexts on primaries & replicas + SearchQueryCurrent int `json:"search.query_current,string"` // current query phase ops on primaries & replicas + SearchQueryTime string `json:"search.query_time"` // time spent in query phase on primaries & replicas, e.g. "0s" + SearchQueryTotal int `json:"search.query_total,string"` // total query phase ops on primaries & replicas + SearchScrollCurrent int `json:"search.scroll_current,string"` // open scroll contexts on primaries & replicas + SearchScrollTime string `json:"search.scroll_time"` // time scroll contexts held open on primaries & replicas, e.g. "0s" + SearchScrollTotal int `json:"search.scroll_total,string"` // completed scroll contexts on primaries & replicas + SearchThrottled bool `json:"search.throttled,string"` // indicates if the index is search throttled + SegmentsCount int `json:"segments.count,string"` // number of segments on primaries & replicas + SegmentsMemory string `json:"segments.memory"` // memory used by segments on primaries & replicas, e.g. "1.3kb" + SegmentsIndexWriterMemory string `json:"segments.index_writer_memory"` // memory used by index writer on primaries & replicas, e.g. "0b" + SegmentsVersionMapMemory string `json:"segments.version_map_memory"` // memory used by version map on primaries & replicas, e.g. "0b" + SegmentsFixedBitsetMemory string `json:"segments.fixed_bitset_memory"` // memory used by fixed bit sets for nested object field types and type filters for types referred in _parent fields on primaries & replicas, e.g. "0b" + SeqNoMax int `json:"seq_no.max,string"` + SeqNoLocalCheckpoint int `json:"seq_no.local_checkpoint,string"` + SeqNoGlobalCheckpoint int `json:"seq_no.global_checkpoint,string"` + WarmerCurrent int `json:"warmer.current,string"` // current warmer ops on primaries & replicas + WarmerTotal int `json:"warmer.total,string"` // total warmer ops on primaries & replicas + WarmerTotalTime string `json:"warmer.total_time"` // time spent in warmers on primaries & replicas, e.g. "47s" +} + +// catShardsResponseRowAliasesMap holds the global map for columns aliases +// the map is used by CatShardsService.buildURL. +// For backwards compatibility some fields are able to have the same aliases +// that means that one alias can be translated to different columns (from different elastic versions) +// example for understanding: rto -> RefreshTotal, RefreshExternalTotal +var catShardsResponseRowAliasesMap = map[string]string{ + "sync_id": "sync_id", + "ur": "unassigned.reason", + "ua": "unassigned.at", + "uf": "unassigned.for", + "ud": "unassigned.details", + "rs": "recoverysource.type", + "cs": "completion.size", + "fm": "fielddata.memory_size", + "fe": "fielddata.evictions", + "qcm": "query_cache.memory_size", + "qce": "query_cache.evictions", + "ft": "flush.total", + "ftt": "flush.total_time", + "gc": "get.current", + "gti": "get.time", + "gto": "get.total", + "geti": "get.exists_time", + "geto": "get.exists_total", + "gmti": "get.missing_time", + "gmto": "get.missing_total", + "idc": "indexing.delete_current", + "idti": "indexing.delete_time", + "idto": "indexing.delete_total", + "iic": "indexing.index_current", + "iiti": "indexing.index_time", + "iito": "indexing.index_total", + "iif": "indexing.index_failed", + "mc": "merges.current", + "mcd": "merges.current_docs", + "mcs": "merges.current_size", + "mt": "merges.total", + "mtd": "merges.total_docs", + "mts": "merges.total_size", + "mtt": "merges.total_time", + "rto": "refresh.total", + "rti": "refresh.time", + // "rto": "refresh.external_total", + // "rti": "refresh.external_time", + "rli": "refresh.listeners", + "sfc": "search.fetch_current", + "sfti": "search.fetch_time", + "sfto": "search.fetch_total", + "so": "search.open_contexts", + "sqc": "search.query_current", + "sqti": "search.query_time", + "sqto": "search.query_total", + "scc": "search.scroll_current", + "scti": "search.scroll_time", + "scto": "search.scroll_total", + "sc": "segments.count", + "sm": "segments.memory", + "siwm": "segments.index_writer_memory", + "svmm": "segments.version_map_memory", + "sfbm": "segments.fixed_bitset_memory", + "sqm": "seq_no.max", + "sql": "seq_no.local_checkpoint", + "sqg": "seq_no.global_checkpoint", + "wc": "warmer.current", + "wto": "warmer.total", + "wtt": "warmer.total_time", +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/clear_scroll.go b/vendor/github.com/olivere/elastic/v7/clear_scroll.go similarity index 51% rename from vendor/gopkg.in/olivere/elastic.v6/clear_scroll.go rename to vendor/github.com/olivere/elastic/v7/clear_scroll.go index e1f4601..a71cad6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/clear_scroll.go +++ b/vendor/github.com/olivere/elastic/v7/clear_scroll.go @@ -7,16 +7,24 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" ) // ClearScrollService clears one or more scroll contexts by their ids. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-scroll.html#_clear_scroll_api +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-scroll.html#_clear_scroll_api // for details. type ClearScrollService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + scrollId []string } @@ -28,6 +36,46 @@ func NewClearScrollService(client *Client) *ClearScrollService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ClearScrollService) Pretty(pretty bool) *ClearScrollService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ClearScrollService) Human(human bool) *ClearScrollService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ClearScrollService) ErrorTrace(errorTrace bool) *ClearScrollService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ClearScrollService) FilterPath(filterPath ...string) *ClearScrollService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ClearScrollService) Header(name string, value string) *ClearScrollService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ClearScrollService) Headers(headers http.Header) *ClearScrollService { + s.headers = headers + return s +} + // ScrollId is a list of scroll IDs to clear. // Use _all to clear all search contexts. func (s *ClearScrollService) ScrollId(scrollIds ...string) *ClearScrollService { @@ -35,12 +83,6 @@ func (s *ClearScrollService) ScrollId(scrollIds ...string) *ClearScrollService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ClearScrollService) Pretty(pretty bool) *ClearScrollService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *ClearScrollService) buildURL() (string, url.Values, error) { // Build URL @@ -48,8 +90,17 @@ func (s *ClearScrollService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } return path, params, nil } @@ -86,10 +137,11 @@ 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, + Method: "DELETE", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -105,4 +157,6 @@ func (s *ClearScrollService) Do(ctx context.Context) (*ClearScrollResponse, erro // ClearScrollResponse is the response of ClearScrollService.Do. type ClearScrollResponse struct { + Succeeded bool `json:"succeeded,omitempty"` + NumFreed int `json:"num_freed,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/client.go b/vendor/github.com/olivere/elastic/v7/client.go similarity index 80% rename from vendor/gopkg.in/olivere/elastic.v6/client.go rename to vendor/github.com/olivere/elastic/v7/client.go index cc44723..a0d3ecb 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/client.go +++ b/vendor/github.com/olivere/elastic/v7/client.go @@ -14,19 +14,18 @@ import ( "net/http/httputil" "net/url" "os" - "regexp" "strings" "sync" "time" "github.com/pkg/errors" - "github.com/olivere/elastic/config" + "github.com/olivere/elastic/v7/config" ) const ( // Version is the current version of Elastic. - Version = "6.1.27" + Version = "7.0.15" // 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. @@ -97,26 +96,36 @@ var ( // noRetries is a retrier that does not retry. noRetries = NewStopRetrier() + + // noDeprecationLog is a no-op for logging deprecations. + noDeprecationLog = func(*http.Request, *http.Response) {} ) +// Doer is an interface to perform HTTP requests. +// It can be used for mocking. +type Doer interface { + Do(*http.Request) (*http.Response, error) +} + // ClientOptionFunc is a function that configures a Client. // It is used in NewClient. type ClientOptionFunc func(*Client) error // Client is an Elasticsearch client. Create one by calling NewClient. type Client struct { - c *http.Client // net/http Client to use for requests + c Doer // e.g. a net/*http.Client to use for requests connsMu sync.RWMutex // connsMu guards the next block conns []*conn // all connections cindex int // index into conns - mu sync.RWMutex // guards the next block - urls []string // set of URLs passed initially to the client - running bool // true if the client's background processes are running - errorlog Logger // error log for critical messages - infolog Logger // information log for e.g. response times - tracelog Logger // trace log for debugging + mu sync.RWMutex // guards the next block + urls []string // set of URLs passed initially to the client + running bool // true if the client's background processes are running + errorlog Logger // error log for critical messages + infolog Logger // information log for e.g. response times + tracelog Logger // trace log for debugging + deprecationlog func(*http.Request, *http.Response) scheme string // http or https healthcheckEnabled bool // healthchecks enabled or disabled healthcheckTimeoutStartup time.Duration // time the healthcheck waits for a response from Elasticsearch on startup @@ -137,6 +146,7 @@ type Client struct { gzipEnabled bool // gzip compression enabled or disabled (default) requiredPlugins []string // list of required plugins retrier Retrier // strategy for retries + headers http.Header // a list of default headers to add to each request } // NewClient creates a new client to work with Elasticsearch. @@ -158,7 +168,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.2/cluster-nodes-info.html#cluster-nodes-info). +// (see https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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. @@ -190,6 +200,119 @@ type Client struct { // An error is also returned when some configuration option is invalid or // the new client cannot sniff the cluster (if enabled). func NewClient(options ...ClientOptionFunc) (*Client, error) { + return DialContext(context.Background(), options...) +} + +// NewClientFromConfig initializes a client from a configuration. +func NewClientFromConfig(cfg *config.Config) (*Client, error) { + options, err := configToOptions(cfg) + if err != nil { + return nil, err + } + return DialContext(context.Background(), options...) +} + +// NewSimpleClient creates a new short-lived Client that can be used in +// use cases where you need e.g. one client per request. +// +// While NewClient by default sets up e.g. periodic health checks +// and sniffing for new nodes in separate goroutines, NewSimpleClient does +// not and is meant as a simple replacement where you don't need all the +// heavy lifting of NewClient. +// +// NewSimpleClient does the following by default: First, all health checks +// are disabled, including timeouts and periodic checks. Second, sniffing +// is disabled, including timeouts and periodic checks. The number of retries +// is set to 1. NewSimpleClient also does not start any goroutines. +// +// Notice that you can still override settings by passing additional options, +// just like with NewClient. +func NewSimpleClient(options ...ClientOptionFunc) (*Client, error) { + c := &Client{ + c: http.DefaultClient, + conns: make([]*conn, 0), + cindex: -1, + scheme: DefaultScheme, + decoder: &DefaultDecoder{}, + healthcheckEnabled: false, + healthcheckTimeoutStartup: off, + healthcheckTimeout: off, + healthcheckInterval: off, + healthcheckStop: make(chan bool), + snifferEnabled: false, + snifferTimeoutStartup: off, + snifferTimeout: off, + snifferInterval: off, + snifferCallback: nopSnifferCallback, + snifferStop: make(chan bool), + sendGetBodyAs: DefaultSendGetBodyAs, + gzipEnabled: DefaultGzipEnabled, + retrier: noRetries, // no retries by default + deprecationlog: noDeprecationLog, + } + + // Run the options on it + for _, option := range options { + if err := option(c); err != nil { + return nil, err + } + } + + // Use a default URL and normalize them + if len(c.urls) == 0 { + c.urls = []string{DefaultURL} + } + c.urls = canonicalize(c.urls...) + + // If the URLs have auth info, use them here as an alternative to SetBasicAuth + if !c.basicAuth { + for _, urlStr := range c.urls { + u, err := url.Parse(urlStr) + if err == nil && u.User != nil { + c.basicAuth = true + c.basicAuthUsername = u.User.Username() + c.basicAuthPassword, _ = u.User.Password() + break + } + } + } + + for _, url := range c.urls { + c.conns = append(c.conns, newConn(url, url)) + } + + // Ensure that we have at least one connection available + if err := c.mustActiveConn(); err != nil { + return nil, err + } + + // Check the required plugins + for _, plugin := range c.requiredPlugins { + found, err := c.HasPlugin(plugin) + if err != nil { + return nil, err + } + if !found { + return nil, fmt.Errorf("elastic: plugin %s not found", plugin) + } + } + + c.mu.Lock() + c.running = true + c.mu.Unlock() + + return c, nil +} + +// Dial will call DialContext with a background context. +func Dial(options ...ClientOptionFunc) (*Client, error) { + return DialContext(context.Background(), options...) +} + +// DialContext will connect to Elasticsearch, just like NewClient does. +// +// The context is honoured in terms of e.g. cancellation. +func DialContext(ctx context.Context, options ...ClientOptionFunc) (*Client, error) { // Set up the client c := &Client{ c: http.DefaultClient, @@ -211,6 +334,7 @@ func NewClient(options ...ClientOptionFunc) (*Client, error) { sendGetBodyAs: DefaultSendGetBodyAs, gzipEnabled: DefaultGzipEnabled, retrier: noRetries, // no retries by default + deprecationlog: noDeprecationLog, } // Run the options on it @@ -241,14 +365,14 @@ func NewClient(options ...ClientOptionFunc) (*Client, error) { // Check if we can make a request to any of the specified URLs if c.healthcheckEnabled { - if err := c.startupHealthcheck(c.healthcheckTimeoutStartup); err != nil { + if err := c.startupHealthcheck(ctx, c.healthcheckTimeoutStartup); err != nil { return nil, err } } if c.snifferEnabled { // Sniff the cluster initially - if err := c.sniff(c.snifferTimeoutStartup); err != nil { + if err := c.sniff(ctx, c.snifferTimeoutStartup); err != nil { return nil, err } } else { @@ -260,7 +384,7 @@ func NewClient(options ...ClientOptionFunc) (*Client, error) { if c.healthcheckEnabled { // Perform an initial health check - c.healthcheck(c.healthcheckTimeoutStartup, true) + c.healthcheck(ctx, c.healthcheckTimeoutStartup, true) } // Ensure that we have at least one connection available if err := c.mustActiveConn(); err != nil { @@ -292,8 +416,19 @@ func NewClient(options ...ClientOptionFunc) (*Client, error) { return c, nil } -// NewClientFromConfig initializes a client from a configuration. -func NewClientFromConfig(cfg *config.Config) (*Client, error) { +// DialWithConfig will use the configuration settings parsed from config package +// to connect to Elasticsearch. +// +// The context is honoured in terms of e.g. cancellation. +func DialWithConfig(ctx context.Context, cfg *config.Config) (*Client, error) { + options, err := configToOptions(cfg) + if err != nil { + return nil, err + } + return DialContext(ctx, options...) +} + +func configToOptions(cfg *config.Config) ([]ClientOptionFunc, error) { var options []ClientOptionFunc if cfg != nil { if cfg.URL != "" { @@ -329,104 +464,16 @@ func NewClientFromConfig(cfg *config.Config) (*Client, error) { if cfg.Sniff != nil { options = append(options, SetSniff(*cfg.Sniff)) } - } - return NewClient(options...) -} - -// NewSimpleClient creates a new short-lived Client that can be used in -// use cases where you need e.g. one client per request. -// -// While NewClient by default sets up e.g. periodic health checks -// and sniffing for new nodes in separate goroutines, NewSimpleClient does -// not and is meant as a simple replacement where you don't need all the -// heavy lifting of NewClient. -// -// NewSimpleClient does the following by default: First, all health checks -// are disabled, including timeouts and periodic checks. Second, sniffing -// is disabled, including timeouts and periodic checks. The number of retries -// is set to 1. NewSimpleClient also does not start any goroutines. -// -// Notice that you can still override settings by passing additional options, -// just like with NewClient. -func NewSimpleClient(options ...ClientOptionFunc) (*Client, error) { - c := &Client{ - c: http.DefaultClient, - conns: make([]*conn, 0), - cindex: -1, - scheme: DefaultScheme, - decoder: &DefaultDecoder{}, - healthcheckEnabled: false, - healthcheckTimeoutStartup: off, - healthcheckTimeout: off, - healthcheckInterval: off, - healthcheckStop: make(chan bool), - snifferEnabled: false, - snifferTimeoutStartup: off, - snifferTimeout: off, - snifferInterval: off, - snifferCallback: nopSnifferCallback, - snifferStop: make(chan bool), - sendGetBodyAs: DefaultSendGetBodyAs, - gzipEnabled: DefaultGzipEnabled, - retrier: noRetries, // no retries by default - } - - // Run the options on it - for _, option := range options { - if err := option(c); err != nil { - return nil, err + if cfg.Healthcheck != nil { + options = append(options, SetHealthcheck(*cfg.Healthcheck)) } } - - // Use a default URL and normalize them - if len(c.urls) == 0 { - c.urls = []string{DefaultURL} - } - c.urls = canonicalize(c.urls...) - - // If the URLs have auth info, use them here as an alternative to SetBasicAuth - if !c.basicAuth { - for _, urlStr := range c.urls { - u, err := url.Parse(urlStr) - if err == nil && u.User != nil { - c.basicAuth = true - c.basicAuthUsername = u.User.Username() - c.basicAuthPassword, _ = u.User.Password() - break - } - } - } - - for _, url := range c.urls { - c.conns = append(c.conns, newConn(url, url)) - } - - // Ensure that we have at least one connection available - if err := c.mustActiveConn(); err != nil { - return nil, err - } - - // Check the required plugins - for _, plugin := range c.requiredPlugins { - found, err := c.HasPlugin(plugin) - if err != nil { - return nil, err - } - if !found { - return nil, fmt.Errorf("elastic: plugin %s not found", plugin) - } - } - - c.mu.Lock() - c.running = true - c.mu.Unlock() - - return c, nil + return options, nil } // SetHttpClient can be used to specify the http.Client to use when making // HTTP requests to Elasticsearch. -func SetHttpClient(httpClient *http.Client) ClientOptionFunc { +func SetHttpClient(httpClient Doer) ClientOptionFunc { return func(c *Client) error { if httpClient != nil { c.c = httpClient @@ -677,6 +724,15 @@ func SetRetrier(retrier Retrier) ClientOptionFunc { } } +// SetHeaders adds a list of default HTTP headers that will be added to +// each requests executed by PerformRequest. +func SetHeaders(headers http.Header) ClientOptionFunc { + return func(c *Client) error { + c.headers = headers + return nil + } +} + // String returns a string representation of the client status. func (c *Client) String() string { c.connsMu.Lock() @@ -816,7 +872,7 @@ func (c *Client) sniffer() { c.snifferStop <- true return case <-ticker.C: - c.sniff(timeout) + c.sniff(context.Background(), timeout) } } } @@ -826,7 +882,7 @@ func (c *Client) sniffer() { // by the preceding sniffing process (if sniffing is enabled). // // If sniffing is disabled, this is a no-op. -func (c *Client) sniff(timeout time.Duration) error { +func (c *Client) sniff(parentCtx context.Context, timeout time.Duration) error { c.mu.RLock() if !c.snifferEnabled { c.mu.RUnlock() @@ -863,7 +919,7 @@ func (c *Client) sniff(timeout time.Duration) error { // Start sniffing on all found URLs ch := make(chan []*conn, len(urls)) - ctx, cancel := context.WithTimeout(context.Background(), timeout) + ctx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() for _, url := range urls { @@ -879,6 +935,13 @@ func (c *Client) sniff(timeout time.Duration) error { return nil } case <-ctx.Done(): + if err := ctx.Err(); err != nil { + switch { + case IsContextErr(err): + return err + } + return errors.Wrapf(ErrNoClient, "sniff timeout: %v", err) + } // We get here if no cluster responds in time return errors.Wrap(ErrNoClient, "sniff timeout") } @@ -908,13 +971,7 @@ func (c *Client) sniffNode(ctx context.Context, url string) []*conn { if err != nil { return nodes } - if res == nil { - return nodes - } - - if res.Body != nil { - defer res.Body.Close() - } + defer res.Body.Close() var info NodesInfoResponse if err := json.NewDecoder(res.Body).Decode(&info); err == nil { @@ -934,25 +991,24 @@ func (c *Client) sniffNode(ctx context.Context, url string) []*conn { return nodes } -// reSniffHostAndPort is used to extract hostname and port from a result -// from a Nodes Info API (example: "inet[/127.0.0.1:9200]"). -var reSniffHostAndPort = regexp.MustCompile(`\/([^:]*):([0-9]+)\]`) - +// extractHostname returns the URL from the http.publish_address setting. func (c *Client) extractHostname(scheme, address string) string { - if strings.HasPrefix(address, "inet") { - m := reSniffHostAndPort.FindStringSubmatch(address) - if len(m) == 3 { - return fmt.Sprintf("%s://%s:%s", scheme, m[1], m[2]) - } - } - s := address - if idx := strings.Index(s, "/"); idx >= 0 { - s = s[idx+1:] - } - if strings.Index(s, ":") < 0 { - return "" + var ( + host string + port string + + addrs = strings.Split(address, "/") + ports = strings.Split(address, ":") + ) + + if len(addrs) > 1 { + host = addrs[0] + } else { + host = strings.Split(addrs[0], ":")[0] } - return fmt.Sprintf("%s://%s", scheme, s) + port = ports[len(ports)-1] + + return fmt.Sprintf("%s://%s:%s", scheme, host, port) } // updateConns updates the clients' connections with new information @@ -967,7 +1023,9 @@ func (c *Client) updateConns(conns []*conn) { for _, conn := range conns { var found bool for _, oldConn := range c.conns { - if oldConn.NodeID() == conn.NodeID() { + // Notice that e.g. in a Kubernetes cluster the NodeID might be + // stable while the URL has changed. + if oldConn.NodeID() == conn.NodeID() && oldConn.URL() == conn.URL() { // Take over the old connection newConns = append(newConns, oldConn) found = true @@ -1003,7 +1061,7 @@ func (c *Client) healthchecker() { c.healthcheckStop <- true return case <-ticker.C: - c.healthcheck(timeout, false) + c.healthcheck(context.Background(), timeout, false) } } } @@ -1012,7 +1070,7 @@ func (c *Client) healthchecker() { // the node state, it marks connections as dead, sets them alive etc. // If healthchecks are disabled and force is false, this is a no-op. // The timeout specifies how long to wait for a response from Elasticsearch. -func (c *Client) healthcheck(timeout time.Duration, force bool) { +func (c *Client) healthcheck(parentCtx context.Context, timeout time.Duration, force bool) { c.mu.RLock() if !c.healthcheckEnabled && !force { c.mu.RUnlock() @@ -1029,7 +1087,7 @@ func (c *Client) healthcheck(timeout time.Duration, force bool) { for _, conn := range conns { // Run the HEAD request against ES with a timeout - ctx, cancel := context.WithTimeout(context.Background(), timeout) + ctx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() // Goroutine executes the HTTP request, returns an error and sets status @@ -1077,7 +1135,7 @@ func (c *Client) healthcheck(timeout time.Duration, force bool) { // startupHealthcheck is used at startup to check if the server is available // at all. -func (c *Client) startupHealthcheck(timeout time.Duration) error { +func (c *Client) startupHealthcheck(parentCtx context.Context, timeout time.Duration) error { c.mu.Lock() urls := c.urls basicAuth := c.basicAuth @@ -1088,7 +1146,8 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error { // If we don't get a connection after "timeout", we bail. var lastErr error start := time.Now() - for { + done := false + for !done { for _, url := range urls { req, err := http.NewRequest("HEAD", url, nil) if err != nil { @@ -1097,7 +1156,7 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error { if basicAuth { req.SetBasicAuth(basicAuthUsername, basicAuthPassword) } - ctx, cancel := context.WithTimeout(req.Context(), timeout) + ctx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() req = req.WithContext(ctx) res, err := c.c.Do(req) @@ -1107,12 +1166,20 @@ func (c *Client) startupHealthcheck(timeout time.Duration) error { lastErr = err } } - time.Sleep(1 * time.Second) - if time.Since(start) > timeout { - break + select { + case <-parentCtx.Done(): + lastErr = parentCtx.Err() + done = true + case <-time.After(1 * time.Second): + if time.Since(start) > timeout { + done = true + } } } if lastErr != nil { + if IsContextErr(lastErr) { + return lastErr + } return errors.Wrapf(ErrNoClient, "health check timeout: %v", lastErr) } return errors.Wrap(ErrNoClient, "health check timeout") @@ -1175,13 +1242,15 @@ func (c *Client) mustActiveConn() error { // PerformRequestOptions must be passed into PerformRequest. type PerformRequestOptions struct { - Method string - Path string - Params url.Values - Body interface{} - ContentType string - IgnoreErrors []int - Retrier Retrier + Method string + Path string + Params url.Values + Body interface{} + ContentType string + IgnoreErrors []int + Retrier Retrier + Headers http.Header + MaxResponseSize int64 } // PerformRequest does a HTTP request to Elasticsearch. @@ -1200,10 +1269,12 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) basicAuthPassword := c.basicAuthPassword sendGetBodyAs := c.sendGetBodyAs gzipEnabled := c.gzipEnabled + healthcheckEnabled := c.healthcheckEnabled retrier := c.retrier if opt.Retrier != nil { retrier = opt.Retrier } + defaultHeaders := c.headers c.mu.RUnlock() var err error @@ -1230,7 +1301,11 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) n++ if !retried { // Force a healtcheck as all connections seem to be dead. - c.healthcheck(timeout, false) + c.healthcheck(ctx, timeout, false) + if healthcheckEnabled { + retried = true + continue + } } wait, ok, rerr := retrier.Retry(ctx, n, nil, nil, err) if rerr != nil { @@ -1253,13 +1328,26 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) c.errorf("elastic: cannot create request for %s %s: %v", strings.ToUpper(opt.Method), conn.URL()+pathWithParams, err) return nil, err } - if basicAuth { req.SetBasicAuth(basicAuthUsername, basicAuthPassword) } if opt.ContentType != "" { req.Header.Set("Content-Type", opt.ContentType) } + if len(opt.Headers) > 0 { + for key, value := range opt.Headers { + for _, v := range value { + req.Header.Add(key, v) + } + } + } + if len(defaultHeaders) > 0 { + for key, value := range defaultHeaders { + for _, v := range value { + req.Header.Add(key, v) + } + } + } // Set body if opt.Body != nil { @@ -1296,30 +1384,31 @@ func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) time.Sleep(wait) continue // try again } - if res.Body != nil { - defer res.Body.Close() - } + defer res.Body.Close() // Tracing c.dumpResponse(res) // Log deprecation warnings as errors - if s := res.Header.Get("Warning"); s != "" { - c.errorf(s) + if len(res.Header["Warning"]) > 0 { + c.deprecationlog((*http.Request)(req), res) + for _, warning := range res.Header["Warning"] { + c.errorf("Deprecation warning: %s", warning) + } } // Check for errors if err := checkResponse((*http.Request)(req), res, opt.IgnoreErrors...); err != nil { // No retry if request succeeded // We still try to return a response. - resp, _ = c.newResponse(res) + resp, _ = c.newResponse(res, opt.MaxResponseSize) return resp, err } // We successfully made a request with this connection conn.MarkAsHealthy() - resp, err = c.newResponse(res) + resp, err = c.newResponse(res, opt.MaxResponseSize) if err != nil { return nil, err } @@ -1391,7 +1480,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.2/docs-reindex.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-reindex.html // for details on the Reindex API. func (c *Client) Reindex() *ReindexService { return NewReindexService(c) @@ -1399,9 +1488,9 @@ func (c *Client) Reindex() *ReindexService { // TermVectors returns information and statistics on terms in the fields // of a particular document. -func (c *Client) TermVectors(index, typ string) *TermvectorsService { +func (c *Client) TermVectors(index string) *TermvectorsService { builder := NewTermvectorsService(c) - builder = builder.Index(index).Type(typ) + builder = builder.Index(index) return builder } @@ -1495,11 +1584,6 @@ func (c *Client) RolloverIndex(alias string) *IndicesRolloverService { return NewIndicesRolloverService(c).Alias(alias) } -// TypeExists allows to check if one or more types exist in one or more indices. -func (c *Client) TypeExists() *IndicesExistsTypeService { - return NewIndicesExistsTypeService(c) -} - // IndexStats provides statistics on different operations happining // in one or more indices. func (c *Client) IndexStats(indices ...string) *IndicesStatsService { @@ -1516,6 +1600,16 @@ func (c *Client) CloseIndex(name string) *IndicesCloseService { return NewIndicesCloseService(c).Index(name) } +// FreezeIndex freezes an index. +func (c *Client) FreezeIndex(name string) *IndicesFreezeService { + return NewIndicesFreezeService(c).Index(name) +} + +// UnfreezeIndex unfreezes an index. +func (c *Client) UnfreezeIndex(name string) *IndicesUnfreezeService { + return NewIndicesUnfreezeService(c).Index(name) +} + // IndexGet retrieves information about one or more indices. // IndexGet is only available for Elasticsearch 1.4 or later. func (c *Client) IndexGet(indices ...string) *IndicesGetService { @@ -1560,6 +1654,20 @@ func (c *Client) Flush(indices ...string) *IndicesFlushService { return NewIndicesFlushService(c).Index(indices...) } +// SyncedFlush performs a synced flush. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-synced-flush.html +// for more details on synched flushes and how they differ from a normal +// Flush. +func (c *Client) SyncedFlush(indices ...string) *IndicesSyncedFlushService { + return NewIndicesSyncedFlushService(c).Index(indices...) +} + +// ClearCache clears caches for one or more indices. +func (c *Client) ClearCache(indices ...string) *IndicesClearCacheService { + return NewIndicesClearCacheService(c).Index(indices...) +} + // Alias enables the caller to add and/or remove aliases. func (c *Client) Alias() *AliasService { return NewAliasService(c) @@ -1646,6 +1754,11 @@ func (c *Client) CatIndices() *CatIndicesService { return NewCatIndicesService(c) } +// CatShards returns information about shards. +func (c *Client) CatShards() *CatShardsService { + return NewCatShardsService(c) +} + // -- Ingest APIs -- // IngestPutPipeline adds pipelines and updates existing pipelines in @@ -1677,6 +1790,12 @@ func (c *Client) ClusterHealth() *ClusterHealthService { return NewClusterHealthService(c) } +// ClusterReroute allows for manual changes to the allocation of +// individual shards in the cluster. +func (c *Client) ClusterReroute() *ClusterRerouteService { + return NewClusterRerouteService(c) +} + // ClusterState retrieves the state of the cluster. func (c *Client) ClusterState() *ClusterStateService { return NewClusterStateService(c) @@ -1720,10 +1839,10 @@ func (c *Client) TasksGetTask() *TasksGetTaskService { // -- Snapshot and Restore -- -// TODO Snapshot Delete -// TODO Snapshot Get -// TODO Snapshot Restore -// TODO Snapshot Status +// SnapshotStatus returns information about the status of a snapshot. +func (c *Client) SnapshotStatus() *SnapshotStatusService { + return NewSnapshotStatusService(c) +} // SnapshotCreate creates a snapshot. func (c *Client) SnapshotCreate(repository string, snapshot string) *SnapshotCreateService { @@ -1735,6 +1854,11 @@ func (c *Client) SnapshotCreateRepository(repository string) *SnapshotCreateRepo return NewSnapshotCreateRepositoryService(c).Repository(repository) } +// SnapshotDelete deletes a snapshot in a snapshot repository. +func (c *Client) SnapshotDelete(repository string, snapshot string) *SnapshotDeleteService { + return NewSnapshotDeleteService(c).Repository(repository).Snapshot(snapshot) +} + // SnapshotDeleteRepository deletes a snapshot repository. func (c *Client) SnapshotDeleteRepository(repositories ...string) *SnapshotDeleteRepositoryService { return NewSnapshotDeleteRepositoryService(c).Repository(repositories...) @@ -1745,11 +1869,21 @@ func (c *Client) SnapshotGetRepository(repositories ...string) *SnapshotGetRepos return NewSnapshotGetRepositoryService(c).Repository(repositories...) } +// SnapshotGet lists snapshot for a repository. +func (c *Client) SnapshotGet(repository string) *SnapshotGetService { + return NewSnapshotGetService(c).Repository(repository) +} + // SnapshotVerifyRepository verifies a snapshot repository. func (c *Client) SnapshotVerifyRepository(repository string) *SnapshotVerifyRepositoryService { return NewSnapshotVerifyRepositoryService(c).Repository(repository) } +// SnapshotRestore restores the specified indices from a given snapshot +func (c *Client) SnapshotRestore(repository string, snapshot string) *SnapshotRestoreService { + return NewSnapshotRestoreService(c).Repository(repository).Snapshot(snapshot) +} + // -- Scripting APIs -- // GetScript reads a stored script in Elasticsearch. @@ -1768,6 +1902,148 @@ func (c *Client) DeleteScript() *DeleteScriptService { return NewDeleteScriptService(c) } +// -- X-Pack General -- + +// XPackInfo gets information on the xpack plugins enabled on the cluster + +func (c *Client) XPackInfo() *XPackInfoService { + return NewXPackInfoService(c) +} + +// -- X-Pack Index Lifecycle Management -- + +// XPackIlmPutLifecycle adds or modifies an ilm policy. +func (c *Client) XPackIlmPutLifecycle() *XPackIlmPutLifecycleService { + return NewXPackIlmPutLifecycleService(c) +} + +// XPackIlmGettLifecycle gets an ilm policy. +func (c *Client) XPackIlmGetLifecycle() *XPackIlmGetLifecycleService { + return NewXPackIlmGetLifecycleService(c) +} + +// XPackIlmDeleteLifecycle deletes an ilm policy. +func (c *Client) XPackIlmDeleteLifecycle() *XPackIlmDeleteLifecycleService { + return NewXPackIlmDeleteLifecycleService(c) +} + +// -- X-Pack Security -- + +// XPackSecurityGetRoleMapping gets a role mapping. +func (c *Client) XPackSecurityGetRoleMapping(roleMappingName string) *XPackSecurityGetRoleMappingService { + return NewXPackSecurityGetRoleMappingService(c).Name(roleMappingName) +} + +// XPackSecurityPutRoleMapping adds a role mapping. +func (c *Client) XPackSecurityPutRoleMapping(roleMappingName string) *XPackSecurityPutRoleMappingService { + return NewXPackSecurityPutRoleMappingService(c).Name(roleMappingName) +} + +// XPackSecurityDeleteRoleMapping deletes a role mapping. +func (c *Client) XPackSecurityDeleteRoleMapping(roleMappingName string) *XPackSecurityDeleteRoleMappingService { + return NewXPackSecurityDeleteRoleMappingService(c).Name(roleMappingName) +} + +// XPackSecurityGetRole gets a role. +func (c *Client) XPackSecurityGetRole(roleName string) *XPackSecurityGetRoleService { + return NewXPackSecurityGetRoleService(c).Name(roleName) +} + +// XPackSecurityPutRole adds a role. +func (c *Client) XPackSecurityPutRole(roleName string) *XPackSecurityPutRoleService { + return NewXPackSecurityPutRoleService(c).Name(roleName) +} + +// XPackSecurityDeleteRole deletes a role. +func (c *Client) XPackSecurityDeleteRole(roleName string) *XPackSecurityDeleteRoleService { + return NewXPackSecurityDeleteRoleService(c).Name(roleName) +} + +// TODO: Clear role cache API +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-clear-role-cache.html + +// XPackSecurityChangePassword changes the password of users in the native realm. +func (c *Client) XPackSecurityChangePassword(username string) *XPackSecurityChangePasswordService { + return NewXPackSecurityChangePasswordService(c).Username(username) +} + +// XPackSecurityGetUser gets details about one or more users. +func (c *Client) XPackSecurityGetUser(usernames ...string) *XPackSecurityGetUserService { + return NewXPackSecurityGetUserService(c).Usernames(usernames...) +} + +// XPackSecurityPutUser adds or updates a user. +func (c *Client) XPackSecurityPutUser(username string) *XPackSecurityPutUserService { + return NewXPackSecurityPutUserService(c).Username(username) +} + +// XPackSecurityEnableUser enables a user. +func (c *Client) XPackSecurityEnableUser(username string) *XPackSecurityEnableUserService { + return NewXPackSecurityEnableUserService(c).Username(username) +} + +// XPackSecurityDisableUser disables a user. +func (c *Client) XPackSecurityDisableUser(username string) *XPackSecurityDisableUserService { + return NewXPackSecurityDisableUserService(c).Username(username) +} + +// XPackSecurityDeleteUser deletes a user. +func (c *Client) XPackSecurityDeleteUser(username string) *XPackSecurityDeleteUserService { + return NewXPackSecurityDeleteUserService(c).Username(username) +} + +// -- X-Pack Watcher -- + +// XPackWatchPut adds a watch. +func (c *Client) XPackWatchPut(watchId string) *XPackWatcherPutWatchService { + return NewXPackWatcherPutWatchService(c).Id(watchId) +} + +// XPackWatchGet gets a watch. +func (c *Client) XPackWatchGet(watchId string) *XPackWatcherGetWatchService { + return NewXPackWatcherGetWatchService(c).Id(watchId) +} + +// XPackWatchDelete deletes a watch. +func (c *Client) XPackWatchDelete(watchId string) *XPackWatcherDeleteWatchService { + return NewXPackWatcherDeleteWatchService(c).Id(watchId) +} + +// XPackWatchExecute executes a watch. +func (c *Client) XPackWatchExecute() *XPackWatcherExecuteWatchService { + return NewXPackWatcherExecuteWatchService(c) +} + +// XPackWatchAck acknowledging a watch. +func (c *Client) XPackWatchAck(watchId string) *XPackWatcherAckWatchService { + return NewXPackWatcherAckWatchService(c).WatchId(watchId) +} + +// XPackWatchActivate activates a watch. +func (c *Client) XPackWatchActivate(watchId string) *XPackWatcherActivateWatchService { + return NewXPackWatcherActivateWatchService(c).WatchId(watchId) +} + +// XPackWatchDeactivate deactivates a watch. +func (c *Client) XPackWatchDeactivate(watchId string) *XPackWatcherDeactivateWatchService { + return NewXPackWatcherDeactivateWatchService(c).WatchId(watchId) +} + +// XPackWatchStats returns the current Watcher metrics. +func (c *Client) XPackWatchStats() *XPackWatcherStatsService { + return NewXPackWatcherStatsService(c) +} + +// XPackWatchStart starts a watch. +func (c *Client) XPackWatchStart() *XPackWatcherStartService { + return NewXPackWatcherStartService(c) +} + +// XPackWatchStop stops a watch. +func (c *Client) XPackWatchStop() *XPackWatcherStopService { + return NewXPackWatcherStopService(c) +} + // -- Helpers and shortcuts -- // ElasticsearchVersion returns the version number of Elasticsearch diff --git a/vendor/gopkg.in/olivere/elastic.v6/cluster_health.go b/vendor/github.com/olivere/elastic/v7/cluster_health.go similarity index 77% rename from vendor/gopkg.in/olivere/elastic.v6/cluster_health.go rename to vendor/github.com/olivere/elastic/v7/cluster_health.go index f960cfe..eba5e22 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cluster_health.go +++ b/vendor/github.com/olivere/elastic/v7/cluster_health.go @@ -7,19 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ClusterHealthService allows to get a very simple status on the health of the cluster. // -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-health.html +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-health.html // for details. type ClusterHealthService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + indices []string level string local *bool @@ -39,6 +46,46 @@ func NewClusterHealthService(client *Client) *ClusterHealthService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ClusterHealthService) Pretty(pretty bool) *ClusterHealthService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ClusterHealthService) Human(human bool) *ClusterHealthService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ClusterHealthService) ErrorTrace(errorTrace bool) *ClusterHealthService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ClusterHealthService) FilterPath(filterPath ...string) *ClusterHealthService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ClusterHealthService) Header(name string, value string) *ClusterHealthService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ClusterHealthService) Headers(headers http.Header) *ClusterHealthService { + s.headers = headers + return s +} + // Index limits the information returned to specific indices. func (s *ClusterHealthService) Index(indices ...string) *ClusterHealthService { s.indices = append(s.indices, indices...) @@ -106,12 +153,6 @@ func (s *ClusterHealthService) WaitForYellowStatus() *ClusterHealthService { return s.WaitForStatus("yellow") } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ClusterHealthService) Pretty(pretty bool) *ClusterHealthService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *ClusterHealthService) buildURL() (string, url.Values, error) { // Build URL @@ -130,8 +171,17 @@ func (s *ClusterHealthService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.level != "" { params.Set("level", s.level) @@ -180,9 +230,10 @@ func (s *ClusterHealthService) Do(ctx context.Context) (*ClusterHealthResponse, // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -211,11 +262,10 @@ type ClusterHealthResponse struct { DelayedUnassignedShards int `json:"delayed_unassigned_shards"` NumberOfPendingTasks int `json:"number_of_pending_tasks"` NumberOfInFlightFetch int `json:"number_of_in_flight_fetch"` - TaskMaxWaitTimeInQueueInMillis int `json:"task_max_waiting_in_queue_millis"` - ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"` - - // Validation failures -> index name -> array of validation failures - ValidationFailures []map[string][]string `json:"validation_failures"` + TaskMaxWaitTimeInQueue string `json:"task_max_waiting_in_queue"` // "0s" + TaskMaxWaitTimeInQueueInMillis int `json:"task_max_waiting_in_queue_millis"` // 0 + ActiveShardsPercent string `json:"active_shards_percent"` // "100.0%" + ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"` // 100.0 // Index name -> index health Indices map[string]*ClusterIndexHealth `json:"indices"` @@ -231,8 +281,6 @@ type ClusterIndexHealth struct { RelocatingShards int `json:"relocating_shards"` InitializingShards int `json:"initializing_shards"` UnassignedShards int `json:"unassigned_shards"` - // Validation failures - ValidationFailures []string `json:"validation_failures"` // Shards by id, e.g. "0" or "1" Shards map[string]*ClusterShardHealth `json:"shards"` } diff --git a/vendor/github.com/olivere/elastic/v7/cluster_reroute.go b/vendor/github.com/olivere/elastic/v7/cluster_reroute.go new file mode 100644 index 0000000..92a9625 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/cluster_reroute.go @@ -0,0 +1,438 @@ +// 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" + "fmt" + "net/http" + "net/url" + "strings" +) + +// ClusterRerouteService allows for manual changes to the allocation of +// individual shards in the cluster. For example, a shard can be moved from +// one node to another explicitly, an allocation can be cancelled, and +// an unassigned shard can be explicitly allocated to a specific node. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-reroute.html +// for details. +type ClusterRerouteService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + metrics []string + dryRun *bool + explain *bool + retryFailed *bool + masterTimeout string + timeout string + commands []AllocationCommand + body interface{} +} + +// NewClusterRerouteService creates a new ClusterRerouteService. +func NewClusterRerouteService(client *Client) *ClusterRerouteService { + return &ClusterRerouteService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ClusterRerouteService) Pretty(pretty bool) *ClusterRerouteService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ClusterRerouteService) Human(human bool) *ClusterRerouteService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ClusterRerouteService) ErrorTrace(errorTrace bool) *ClusterRerouteService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ClusterRerouteService) FilterPath(filterPath ...string) *ClusterRerouteService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ClusterRerouteService) Header(name string, value string) *ClusterRerouteService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ClusterRerouteService) Headers(headers http.Header) *ClusterRerouteService { + s.headers = headers + return s +} + +// Metric limits the information returned to the specified metric. +// It can be one of: "_all", "blocks", "metadata", "nodes", "routing_table", "master_node", "version". +// Defaults to all but metadata. +func (s *ClusterRerouteService) Metric(metrics ...string) *ClusterRerouteService { + s.metrics = append(s.metrics, metrics...) + return s +} + +// DryRun indicates whether to simulate the operation only and return the +// resulting state. +func (s *ClusterRerouteService) DryRun(dryRun bool) *ClusterRerouteService { + s.dryRun = &dryRun + return s +} + +// Explain, when set to true, returns an explanation of why the commands +// can or cannot be executed. +func (s *ClusterRerouteService) Explain(explain bool) *ClusterRerouteService { + s.explain = &explain + return s +} + +// RetryFailed indicates whether to retry allocation of shards that are blocked +// due to too many subsequent allocation failures. +func (s *ClusterRerouteService) RetryFailed(retryFailed bool) *ClusterRerouteService { + s.retryFailed = &retryFailed + return s +} + +// MasterTimeout specifies an explicit timeout for connection to master. +func (s *ClusterRerouteService) MasterTimeout(masterTimeout string) *ClusterRerouteService { + s.masterTimeout = masterTimeout + return s +} + +// Timeout specifies an explicit operationtimeout. +func (s *ClusterRerouteService) Timeout(timeout string) *ClusterRerouteService { + s.timeout = timeout + return s +} + +// Add adds one or more commands to be executed. +func (s *ClusterRerouteService) Add(commands ...AllocationCommand) *ClusterRerouteService { + s.commands = append(s.commands, commands...) + return s +} + +// Body specifies the body to be sent. +// If you specify Body, the commands passed via Add are ignored. +// In other words: Body takes precedence over Add. +func (s *ClusterRerouteService) Body(body interface{}) *ClusterRerouteService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *ClusterRerouteService) buildURL() (string, url.Values, error) { + // Build URL + path := "/_cluster/reroute" + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.dryRun; v != nil { + params.Set("dry_run", fmt.Sprint(*v)) + } + if v := s.explain; v != nil { + params.Set("explain", fmt.Sprint(*v)) + } + if v := s.retryFailed; v != nil { + params.Set("retry_failed", fmt.Sprint(*v)) + } + if len(s.metrics) > 0 { + params.Set("metric", strings.Join(s.metrics, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *ClusterRerouteService) Validate() error { + if s.body == nil && len(s.commands) == 0 { + return errors.New("missing allocate commands or raw body") + } + return nil +} + +// Do executes the operation. +func (s *ClusterRerouteService) Do(ctx context.Context) (*ClusterRerouteResponse, 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.body != nil { + body = s.body + } else { + commands := make([]interface{}, len(s.commands)) + for i, cmd := range s.commands { + src, err := cmd.Source() + if err != nil { + return nil, err + } + commands[i] = map[string]interface{}{ + cmd.Name(): src, + } + } + query := make(map[string]interface{}) + query["commands"] = commands + body = query + } + + // Get HTTP response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(ClusterRerouteResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// ClusterRerouteResponse is the response of ClusterRerouteService.Do. +type ClusterRerouteResponse struct { + State *ClusterStateResponse `json:"state"` + Explanations []RerouteExplanation `json:"explanations,omitempty"` +} + +// RerouteExplanation is returned in ClusterRerouteResponse if +// the "explain" parameter is set to "true". +type RerouteExplanation struct { + Command string `json:"command"` + Parameters map[string]interface{} `json:"parameters"` + Decisions []RerouteDecision `json:"decisions"` +} + +// RerouteDecision is a decision the decider made while rerouting. +type RerouteDecision interface{} + +// -- Allocation commands -- + +// AllocationCommand is a command to be executed in a call +// to Cluster Reroute API. +type AllocationCommand interface { + Name() string + Source() (interface{}, error) +} + +var _ AllocationCommand = (*MoveAllocationCommand)(nil) + +// MoveAllocationCommand moves a shard from a specific node to +// another node. +type MoveAllocationCommand struct { + index string + shardId int + fromNode string + toNode string +} + +// NewMoveAllocationCommand creates a new MoveAllocationCommand. +func NewMoveAllocationCommand(index string, shardId int, fromNode, toNode string) *MoveAllocationCommand { + return &MoveAllocationCommand{ + index: index, + shardId: shardId, + fromNode: fromNode, + toNode: toNode, + } +} + +// Name of the command in a request to the Cluster Reroute API. +func (cmd *MoveAllocationCommand) Name() string { return "move" } + +// Source generates the (inner) JSON to be used when serializing the command. +func (cmd *MoveAllocationCommand) Source() (interface{}, error) { + source := make(map[string]interface{}) + source["index"] = cmd.index + source["shard"] = cmd.shardId + source["from_node"] = cmd.fromNode + source["to_node"] = cmd.toNode + return source, nil +} + +var _ AllocationCommand = (*CancelAllocationCommand)(nil) + +// CancelAllocationCommand cancels relocation, or recovery of a given shard on a node. +type CancelAllocationCommand struct { + index string + shardId int + node string + allowPrimary bool +} + +// NewCancelAllocationCommand creates a new CancelAllocationCommand. +func NewCancelAllocationCommand(index string, shardId int, node string, allowPrimary bool) *CancelAllocationCommand { + return &CancelAllocationCommand{ + index: index, + shardId: shardId, + node: node, + allowPrimary: allowPrimary, + } +} + +// Name of the command in a request to the Cluster Reroute API. +func (cmd *CancelAllocationCommand) Name() string { return "cancel" } + +// Source generates the (inner) JSON to be used when serializing the command. +func (cmd *CancelAllocationCommand) Source() (interface{}, error) { + source := make(map[string]interface{}) + source["index"] = cmd.index + source["shard"] = cmd.shardId + source["node"] = cmd.node + source["allow_primary"] = cmd.allowPrimary + return source, nil +} + +var _ AllocationCommand = (*AllocateStalePrimaryAllocationCommand)(nil) + +// AllocateStalePrimaryAllocationCommand allocates an unassigned stale +// primary shard to a specific node. Use with extreme care as this will +// result in data loss. Allocation deciders are ignored. +type AllocateStalePrimaryAllocationCommand struct { + index string + shardId int + node string + acceptDataLoss bool +} + +// NewAllocateStalePrimaryAllocationCommand creates a new +// AllocateStalePrimaryAllocationCommand. +func NewAllocateStalePrimaryAllocationCommand(index string, shardId int, node string, acceptDataLoss bool) *AllocateStalePrimaryAllocationCommand { + return &AllocateStalePrimaryAllocationCommand{ + index: index, + shardId: shardId, + node: node, + acceptDataLoss: acceptDataLoss, + } +} + +// Name of the command in a request to the Cluster Reroute API. +func (cmd *AllocateStalePrimaryAllocationCommand) Name() string { return "allocate_stale_primary" } + +// Source generates the (inner) JSON to be used when serializing the command. +func (cmd *AllocateStalePrimaryAllocationCommand) Source() (interface{}, error) { + source := make(map[string]interface{}) + source["index"] = cmd.index + source["shard"] = cmd.shardId + source["node"] = cmd.node + source["accept_data_loss"] = cmd.acceptDataLoss + return source, nil +} + +var _ AllocationCommand = (*AllocateReplicaAllocationCommand)(nil) + +// AllocateReplicaAllocationCommand allocates an unassigned replica shard +// to a specific node. Checks if allocation deciders allow allocation. +type AllocateReplicaAllocationCommand struct { + index string + shardId int + node string +} + +// NewAllocateReplicaAllocationCommand creates a new +// AllocateReplicaAllocationCommand. +func NewAllocateReplicaAllocationCommand(index string, shardId int, node string) *AllocateReplicaAllocationCommand { + return &AllocateReplicaAllocationCommand{ + index: index, + shardId: shardId, + node: node, + } +} + +// Name of the command in a request to the Cluster Reroute API. +func (cmd *AllocateReplicaAllocationCommand) Name() string { return "allocate_replica" } + +// Source generates the (inner) JSON to be used when serializing the command. +func (cmd *AllocateReplicaAllocationCommand) Source() (interface{}, error) { + source := make(map[string]interface{}) + source["index"] = cmd.index + source["shard"] = cmd.shardId + source["node"] = cmd.node + return source, nil +} + +// AllocateEmptyPrimaryAllocationCommand allocates an unassigned empty +// primary shard to a specific node. Use with extreme care as this will +// result in data loss. Allocation deciders are ignored. +type AllocateEmptyPrimaryAllocationCommand struct { + index string + shardId int + node string + acceptDataLoss bool +} + +// NewAllocateEmptyPrimaryAllocationCommand creates a new +// AllocateEmptyPrimaryAllocationCommand. +func NewAllocateEmptyPrimaryAllocationCommand(index string, shardId int, node string, acceptDataLoss bool) *AllocateEmptyPrimaryAllocationCommand { + return &AllocateEmptyPrimaryAllocationCommand{ + index: index, + shardId: shardId, + node: node, + acceptDataLoss: acceptDataLoss, + } +} + +// Name of the command in a request to the Cluster Reroute API. +func (cmd *AllocateEmptyPrimaryAllocationCommand) Name() string { return "allocate_empty_primary" } + +// Source generates the (inner) JSON to be used when serializing the command. +func (cmd *AllocateEmptyPrimaryAllocationCommand) Source() (interface{}, error) { + source := make(map[string]interface{}) + source["index"] = cmd.index + source["shard"] = cmd.shardId + source["node"] = cmd.node + source["accept_data_loss"] = cmd.acceptDataLoss + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/cluster_state.go b/vendor/github.com/olivere/elastic/v7/cluster_state.go similarity index 64% rename from vendor/gopkg.in/olivere/elastic.v6/cluster_state.go rename to vendor/github.com/olivere/elastic/v7/cluster_state.go index 1391951..7d30086 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cluster_state.go +++ b/vendor/github.com/olivere/elastic/v7/cluster_state.go @@ -7,19 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ClusterStateService allows to get a comprehensive state information of the whole cluster. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cluster-state.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-state.html // for details. type ClusterStateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + indices []string metrics []string allowNoIndices *bool @@ -39,6 +46,46 @@ func NewClusterStateService(client *Client) *ClusterStateService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ClusterStateService) Pretty(pretty bool) *ClusterStateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ClusterStateService) Human(human bool) *ClusterStateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ClusterStateService) ErrorTrace(errorTrace bool) *ClusterStateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ClusterStateService) FilterPath(filterPath ...string) *ClusterStateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ClusterStateService) Header(name string, value string) *ClusterStateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ClusterStateService) Headers(headers http.Header) *ClusterStateService { + s.headers = headers + return s +} + // Index is a list of index names. Use _all or an empty string to // perform the operation on all indices. func (s *ClusterStateService) Index(indices ...string) *ClusterStateService { @@ -95,12 +142,6 @@ func (s *ClusterStateService) MasterTimeout(masterTimeout string) *ClusterStateS return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ClusterStateService) Pretty(pretty bool) *ClusterStateService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *ClusterStateService) buildURL() (string, url.Values, error) { // Build URL @@ -122,8 +163,17 @@ func (s *ClusterStateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -166,9 +216,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -184,16 +235,17 @@ func (s *ClusterStateService) Do(ctx context.Context) (*ClusterStateResponse, er // ClusterStateResponse is the response of ClusterStateService.Do. type ClusterStateResponse struct { - ClusterName string `json:"cluster_name"` - Version int64 `json:"version"` - StateUUID string `json:"state_uuid"` - MasterNode string `json:"master_node"` - Blocks map[string]*clusterBlocks `json:"blocks"` - Nodes map[string]*discoveryNode `json:"nodes"` - Metadata *clusterStateMetadata `json:"metadata"` - RoutingTable map[string]*clusterStateRoutingTable `json:"routing_table"` - RoutingNodes *clusterStateRoutingNode `json:"routing_nodes"` - Customs map[string]interface{} `json:"customs"` + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Version int64 `json:"version"` + StateUUID string `json:"state_uuid"` + MasterNode string `json:"master_node"` + Blocks map[string]*clusterBlocks `json:"blocks"` + Nodes map[string]*discoveryNode `json:"nodes"` + Metadata *clusterStateMetadata `json:"metadata"` + RoutingTable *clusterStateRoutingTable `json:"routing_table"` + RoutingNodes *clusterStateRoutingNode `json:"routing_nodes"` + Customs map[string]interface{} `json:"customs"` } type clusterBlocks struct { @@ -209,21 +261,34 @@ type clusterBlock struct { } type clusterStateMetadata struct { - ClusterUUID string `json:"cluster_uuid"` - Templates map[string]*indexTemplateMetaData `json:"templates"` // template name -> index template metadata - Indices map[string]*indexMetaData `json:"indices"` // index name _> meta data - RoutingTable struct { + ClusterUUID string `json:"cluster_uuid"` + ClusterUUIDCommitted string `json:"cluster_uuid_committed"` + ClusterCoordination *clusterCoordinationMetaData `json:"cluster_coordination"` + Templates map[string]*indexTemplateMetaData `json:"templates"` // template name -> index template metadata + Indices map[string]*indexMetaData `json:"indices"` // index name _> meta data + RoutingTable struct { Indices map[string]*indexRoutingTable `json:"indices"` // index name -> routing table } `json:"routing_table"` RoutingNodes struct { Unassigned []*shardRouting `json:"unassigned"` Nodes []*shardRouting `json:"nodes"` } `json:"routing_nodes"` - Customs map[string]interface{} `json:"customs"` + Customs map[string]interface{} `json:"customs"` + Ingest map[string]interface{} `json:"ingest"` + StoredScripts map[string]interface{} `json:"stored_scripts"` + IndexGraveyard map[string]interface{} `json:"index-graveyard"` +} + +type clusterCoordinationMetaData struct { + Term int64 `json:"term"` + LastCommittedConfig interface{} `json:"last_committed_config,omitempty"` + LastAcceptedConfig interface{} `json:"last_accepted_config,omitempty"` + VotingConfigExclusions []interface{} `json:"voting_config_exclusions,omitempty"` } type discoveryNode struct { Name string `json:"name"` // server name, e.g. "es1" + EphemeralID string `json:"ephemeral_id"` // e.g. "paHSLpn6QyuVy_n-GM1JAQ" TransportAddress string `json:"transport_address"` // e.g. inet[/1.2.3.4:9300] Attributes map[string]interface{} `json:"attributes"` // e.g. { "data": true, "master": true } } @@ -246,10 +311,12 @@ type indexTemplateMetaData struct { } type indexMetaData struct { - State string `json:"state"` - Settings map[string]interface{} `json:"settings"` - Mappings map[string]interface{} `json:"mappings"` - Aliases []string `json:"aliases"` // e.g. [ "alias1", "alias2" ] + State string `json:"state"` + Settings map[string]interface{} `json:"settings"` + Mappings map[string]interface{} `json:"mappings"` + Aliases []string `json:"aliases"` // e.g. [ "alias1", "alias2" ] + PrimaryTerms map[string]interface{} `json:"primary_terms"` + InSyncAllocations map[string]interface{} `json:"in_sync_allocations"` } type indexRoutingTable struct { diff --git a/vendor/gopkg.in/olivere/elastic.v6/cluster_stats.go b/vendor/github.com/olivere/elastic/v7/cluster_stats.go similarity index 64% rename from vendor/gopkg.in/olivere/elastic.v6/cluster_stats.go rename to vendor/github.com/olivere/elastic/v7/cluster_stats.go index 07bc3ae..711c2a7 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/cluster_stats.go +++ b/vendor/github.com/olivere/elastic/v7/cluster_stats.go @@ -7,20 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ClusterStatsService is documented at -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/cluster-stats.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-stats.html. type ClusterStatsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + nodeId []string flatSettings *bool - human *bool } // NewClusterStatsService creates a new ClusterStatsService. @@ -31,27 +37,55 @@ func NewClusterStatsService(client *Client) *ClusterStatsService { } } -// NodeId is documented as: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -func (s *ClusterStatsService) NodeId(nodeId []string) *ClusterStatsService { - s.nodeId = nodeId +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ClusterStatsService) Pretty(pretty bool) *ClusterStatsService { + s.pretty = &pretty return s } -// FlatSettings is documented as: Return settings in flat format (default: false). -func (s *ClusterStatsService) FlatSettings(flatSettings bool) *ClusterStatsService { - s.flatSettings = &flatSettings +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ClusterStatsService) Human(human bool) *ClusterStatsService { + s.human = &human return s } -// Human is documented as: Whether to return time and byte values in human-readable format.. -func (s *ClusterStatsService) Human(human bool) *ClusterStatsService { - s.human = &human +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ClusterStatsService) ErrorTrace(errorTrace bool) *ClusterStatsService { + s.errorTrace = &errorTrace return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ClusterStatsService) Pretty(pretty bool) *ClusterStatsService { - s.pretty = pretty +// FilterPath specifies a list of filters used to reduce the response. +func (s *ClusterStatsService) FilterPath(filterPath ...string) *ClusterStatsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ClusterStatsService) Header(name string, value string) *ClusterStatsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ClusterStatsService) Headers(headers http.Header) *ClusterStatsService { + s.headers = headers + return s +} + +// NodeId is documented as: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. +func (s *ClusterStatsService) NodeId(nodeId []string) *ClusterStatsService { + s.nodeId = nodeId + return s +} + +// FlatSettings is documented as: Return settings in flat format (default: false). +func (s *ClusterStatsService) FlatSettings(flatSettings bool) *ClusterStatsService { + s.flatSettings = &flatSettings return s } @@ -77,15 +111,21 @@ func (s *ClusterStatsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.flatSettings != nil { params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings)) } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) - } return path, params, nil } @@ -109,9 +149,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -127,25 +168,24 @@ func (s *ClusterStatsService) Do(ctx context.Context) (*ClusterStatsResponse, er // ClusterStatsResponse is the response of ClusterStatsService.Do. type ClusterStatsResponse struct { + NodesStats *ShardsInfo `json:"_nodes,omitempty"` Timestamp int64 `json:"timestamp"` ClusterName string `json:"cluster_name"` - ClusterUUID string `json:"uuid"` - Status string `json:"status"` + ClusterUUID string `json:"cluster_uuid"` + Status string `json:"status,omitempty"` // e.g. green Indices *ClusterStatsIndices `json:"indices"` Nodes *ClusterStatsNodes `json:"nodes"` } type ClusterStatsIndices struct { - Count int `json:"count"` - Shards *ClusterStatsIndicesShards `json:"shards"` - Docs *ClusterStatsIndicesDocs `json:"docs"` - Store *ClusterStatsIndicesStore `json:"store"` - FieldData *ClusterStatsIndicesFieldData `json:"fielddata"` - FilterCache *ClusterStatsIndicesFilterCache `json:"filter_cache"` - IdCache *ClusterStatsIndicesIdCache `json:"id_cache"` - Completion *ClusterStatsIndicesCompletion `json:"completion"` - Segments *ClusterStatsIndicesSegments `json:"segments"` - Percolate *ClusterStatsIndicesPercolate `json:"percolate"` + Count int `json:"count"` // number of indices + Shards *ClusterStatsIndicesShards `json:"shards"` + Docs *ClusterStatsIndicesDocs `json:"docs"` + Store *ClusterStatsIndicesStore `json:"store"` + FieldData *ClusterStatsIndicesFieldData `json:"fielddata"` + QueryCache *ClusterStatsIndicesQueryCache `json:"query_cache"` + Completion *ClusterStatsIndicesCompletion `json:"completion"` + Segments *IndexStatsSegments `json:"segments"` } type ClusterStatsIndicesShards struct { @@ -190,52 +230,33 @@ type ClusterStatsIndicesFieldData struct { Fields map[string]struct { MemorySize string `json:"memory_size"` // e.g. "61.3kb" MemorySizeInBytes int64 `json:"memory_size_in_bytes"` - } `json:"fields"` + } `json:"fields,omitempty"` } -type ClusterStatsIndicesFilterCache struct { +type ClusterStatsIndicesQueryCache struct { MemorySize string `json:"memory_size"` // e.g. "61.3kb" MemorySizeInBytes int64 `json:"memory_size_in_bytes"` + TotalCount int64 `json:"total_count"` + HitCount int64 `json:"hit_count"` + MissCount int64 `json:"miss_count"` + CacheSize int64 `json:"cache_size"` + CacheCount int64 `json:"cache_count"` Evictions int64 `json:"evictions"` } -type ClusterStatsIndicesIdCache struct { - MemorySize string `json:"memory_size"` // e.g. "61.3kb" - MemorySizeInBytes int64 `json:"memory_size_in_bytes"` -} - type ClusterStatsIndicesCompletion struct { Size string `json:"size"` // e.g. "61.3kb" SizeInBytes int64 `json:"size_in_bytes"` Fields map[string]struct { Size string `json:"size"` // e.g. "61.3kb" SizeInBytes int64 `json:"size_in_bytes"` - } `json:"fields"` -} - -type ClusterStatsIndicesSegments struct { - Count int64 `json:"count"` - Memory string `json:"memory"` // e.g. "61.3kb" - MemoryInBytes int64 `json:"memory_in_bytes"` - IndexWriterMemory string `json:"index_writer_memory"` // e.g. "61.3kb" - IndexWriterMemoryInBytes int64 `json:"index_writer_memory_in_bytes"` - IndexWriterMaxMemory string `json:"index_writer_max_memory"` // e.g. "61.3kb" - IndexWriterMaxMemoryInBytes int64 `json:"index_writer_max_memory_in_bytes"` - VersionMapMemory string `json:"version_map_memory"` // e.g. "61.3kb" - VersionMapMemoryInBytes int64 `json:"version_map_memory_in_bytes"` - FixedBitSet string `json:"fixed_bit_set"` // e.g. "61.3kb" - FixedBitSetInBytes int64 `json:"fixed_bit_set_memory_in_bytes"` -} - -type ClusterStatsIndicesPercolate struct { - Total int64 `json:"total"` - // TODO(oe) The JSON tag here is wrong as of ES 1.5.2 it seems - Time string `json:"get_time"` // e.g. "1s" - TimeInBytes int64 `json:"time_in_millis"` - Current int64 `json:"current"` - MemorySize string `json:"memory_size"` // e.g. "61.3kb" - MemorySizeInBytes int64 `json:"memory_sitze_in_bytes"` - Queries int64 `json:"queries"` + } `json:"fields,omitempty"` +} + +type ClusterStatsIndicesSegmentsFile struct { + Size string `json:"size"` // e.g. "61.3kb" + SizeInBytes int64 `json:"size_in_bytes"` + Description string `json:"description,omitempty"` } // --- @@ -248,6 +269,10 @@ type ClusterStatsNodes struct { JVM *ClusterStatsNodesJvmStats `json:"jvm"` FS *ClusterStatsNodesFsStats `json:"fs"` Plugins []*ClusterStatsNodesPlugin `json:"plugins"` + + NetworkTypes *ClusterStatsNodesNetworkTypes `json:"network_types"` + DiscoveryTypes *ClusterStatsNodesDiscoveryTypes `json:"discovery_types"` + PackagingTypes *ClusterStatsNodesPackagingTypes `json:"packaging_types"` } type ClusterStatsNodesCount struct { @@ -259,14 +284,29 @@ type ClusterStatsNodesCount struct { } type ClusterStatsNodesOsStats struct { - AvailableProcessors int `json:"available_processors"` - Mem *ClusterStatsNodesOsStatsMem `json:"mem"` - CPU []*ClusterStatsNodesOsStatsCPU `json:"cpu"` + AvailableProcessors int `json:"available_processors"` + AllocatedProcessors int `json:"allocated_processors"` + Names []struct { + Name string `json:"name"` + Value int `json:"count"` + } `json:"names"` + PrettyNames []struct { + PrettyName string `json:"pretty_name"` + Value int `json:"count"` + } `json:"pretty_names"` + Mem *ClusterStatsNodesOsStatsMem `json:"mem"` + // CPU []*ClusterStatsNodesOsStatsCPU `json:"cpu"` } type ClusterStatsNodesOsStatsMem struct { Total string `json:"total"` // e.g. "16gb" TotalInBytes int64 `json:"total_in_bytes"` + Free string `json:"free"` // e.g. "12gb" + FreeInBytes int64 `json:"free_in_bytes"` + Used string `json:"used"` // e.g. "4gb" + UsedInBytes int64 `json:"used_in_bytes"` + FreePercent int `json:"free_percent"` + UsedPercent int `json:"used_percent"` } type ClusterStatsNodesOsStatsCPU struct { @@ -305,11 +345,13 @@ type ClusterStatsNodesJvmStats struct { } type ClusterStatsNodesJvmStatsVersion struct { - Version string `json:"version"` // e.g. "1.8.0_45" - VMName string `json:"vm_name"` // e.g. "Java HotSpot(TM) 64-Bit Server VM" - VMVersion string `json:"vm_version"` // e.g. "25.45-b02" - VMVendor string `json:"vm_vendor"` // e.g. "Oracle Corporation" - Count int `json:"count"` + Version string `json:"version"` // e.g. "1.8.0_45" + VMName string `json:"vm_name"` // e.g. "Java HotSpot(TM) 64-Bit Server VM" + VMVersion string `json:"vm_version"` // e.g. "25.45-b02" + VMVendor string `json:"vm_vendor"` // e.g. "Oracle Corporation" + BundledJDK bool `json:"bundled_jdk"` + UsingBundledJDK bool `json:"using_bundled_jdk"` + Count int `json:"count"` } type ClusterStatsNodesJvmStatsMem struct { @@ -350,3 +392,18 @@ type ClusterStatsNodesPlugin struct { JVM bool `json:"jvm"` Site bool `json:"site"` } + +type ClusterStatsNodesNetworkTypes struct { + TransportTypes map[string]interface{} `json:"transport_types"` // e.g. "netty4": 1 + HTTPTypes map[string]interface{} `json:"http_types"` // e.g. "netty4": 1 +} + +type ClusterStatsNodesDiscoveryTypes interface{} + +type ClusterStatsNodesPackagingTypes []*ClusterStatsNodesPackagingType + +type ClusterStatsNodesPackagingType struct { + Flavor string `json:"flavor"` // e.g. "oss" + Type string `json:"type"` // e.g. "docker" + Count int `json:"count"` // e.g. 1 +} diff --git a/vendor/github.com/olivere/elastic/config/config.go b/vendor/github.com/olivere/elastic/v7/config/config.go similarity index 100% rename from vendor/github.com/olivere/elastic/config/config.go rename to vendor/github.com/olivere/elastic/v7/config/config.go diff --git a/vendor/github.com/olivere/elastic/config/doc.go b/vendor/github.com/olivere/elastic/v7/config/doc.go similarity index 100% rename from vendor/github.com/olivere/elastic/config/doc.go rename to vendor/github.com/olivere/elastic/v7/config/doc.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/connection.go b/vendor/github.com/olivere/elastic/v7/connection.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/connection.go rename to vendor/github.com/olivere/elastic/v7/connection.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/count.go b/vendor/github.com/olivere/elastic/v7/count.go similarity index 79% rename from vendor/gopkg.in/olivere/elastic.v6/count.go rename to vendor/github.com/olivere/elastic/v7/count.go index 8dde488..d1c75be 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/count.go +++ b/vendor/github.com/olivere/elastic/v7/count.go @@ -7,18 +7,25 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // CountService is a convenient service for determining the // number of documents in an index. Use SearchService with // a SearchType of count for counting with queries etc. type CountService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string allowNoIndices *bool @@ -47,6 +54,46 @@ func NewCountService(client *Client) *CountService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *CountService) Pretty(pretty bool) *CountService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *CountService) Human(human bool) *CountService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *CountService) ErrorTrace(errorTrace bool) *CountService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *CountService) FilterPath(filterPath ...string) *CountService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *CountService) Header(name string, value string) *CountService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *CountService) Headers(headers http.Header) *CountService { + s.headers = headers + return s +} + // Index sets the names of the indices to restrict the results. func (s *CountService) Index(index ...string) *CountService { if s.index == nil { @@ -57,6 +104,9 @@ func (s *CountService) Index(index ...string) *CountService { } // Type sets the types to use to restrict the results. +// +// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to +// filter on a field on the document. func (s *CountService) Type(typ ...string) *CountService { if s.typ == nil { s.typ = make([]string, 0) @@ -166,12 +216,6 @@ func (s *CountService) TerminateAfter(terminateAfter int) *CountService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *CountService) Pretty(pretty bool) *CountService { - s.pretty = pretty - return s -} - // BodyJson specifies the query to restrict the results specified with the // Query DSL (optional). The interface{} will be serialized to a JSON document, // so use a map[string]interface{}. @@ -214,8 +258,17 @@ func (s *CountService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -298,10 +351,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return 0, err @@ -321,6 +375,7 @@ func (s *CountService) Do(ctx context.Context) (int64, error) { // CountResponse is the response of using the Count API. type CountResponse struct { - Count int64 `json:"count"` - Shards shardsInfo `json:"_shards,omitempty"` + Count int64 `json:"count"` + TerminatedEarly bool `json:"terminated_early,omitempty"` + Shards *ShardsInfo `json:"_shards,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/decoder.go b/vendor/github.com/olivere/elastic/v7/decoder.go similarity index 68% rename from vendor/gopkg.in/olivere/elastic.v6/decoder.go rename to vendor/github.com/olivere/elastic/v7/decoder.go index 9cd2cf7..9133ccd 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/decoder.go +++ b/vendor/github.com/olivere/elastic/v7/decoder.go @@ -5,6 +5,7 @@ package elastic import ( + "bytes" "encoding/json" ) @@ -24,3 +25,14 @@ type DefaultDecoder struct{} func (u *DefaultDecoder) Decode(data []byte, v interface{}) error { return json.Unmarshal(data, v) } + +// NumberDecoder uses json.NewDecoder, with UseNumber() enabled, from +// the Go standard library to decode JSON data. +type NumberDecoder struct{} + +// Decode decodes with json.Unmarshal from the Go standard library. +func (u *NumberDecoder) Decode(data []byte, v interface{}) error { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + return dec.Decode(v) +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/delete.go b/vendor/github.com/olivere/elastic/v7/delete.go similarity index 65% rename from vendor/gopkg.in/olivere/elastic.v6/delete.go rename to vendor/github.com/olivere/elastic/v7/delete.go index baac24e..f694701 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/delete.go +++ b/vendor/github.com/olivere/elastic/v7/delete.go @@ -9,18 +9,25 @@ import ( "fmt" "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/docs-delete.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-delete.html // for details. type DeleteService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string index string typ string @@ -31,16 +38,61 @@ type DeleteService struct { waitForActiveShards string parent string refresh string + ifSeqNo *int64 + ifPrimaryTerm *int64 } // NewDeleteService creates a new DeleteService. func NewDeleteService(client *Client) *DeleteService { return &DeleteService{ client: client, + typ: "_doc", + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *DeleteService) Pretty(pretty bool) *DeleteService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *DeleteService) Human(human bool) *DeleteService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *DeleteService) ErrorTrace(errorTrace bool) *DeleteService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *DeleteService) FilterPath(filterPath ...string) *DeleteService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *DeleteService) Header(name string, value string) *DeleteService { + if s.headers == nil { + s.headers = http.Header{} } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *DeleteService) Headers(headers http.Header) *DeleteService { + s.headers = headers + return s } // Type is the type of the document. +// +// Deprecated: Types are in the process of being removed. func (s *DeleteService) Type(typ string) *DeleteService { s.typ = typ return s @@ -100,16 +152,24 @@ func (s *DeleteService) Parent(parent string) *DeleteService { // Refresh the index after performing the operation. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *DeleteService) Refresh(refresh string) *DeleteService { s.refresh = refresh return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *DeleteService) Pretty(pretty bool) *DeleteService { - s.pretty = pretty +// IfSeqNo indicates to only perform the delete operation if the last +// operation that has changed the document has the specified sequence number. +func (s *DeleteService) IfSeqNo(seqNo int64) *DeleteService { + s.ifSeqNo = &seqNo + return s +} + +// IfPrimaryTerm indicates to only perform the delete operation if the +// last operation that has changed the document has the specified primary term. +func (s *DeleteService) IfPrimaryTerm(primaryTerm int64) *DeleteService { + s.ifPrimaryTerm = &primaryTerm return s } @@ -127,8 +187,17 @@ func (s *DeleteService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.refresh != "" { params.Set("refresh", s.refresh) @@ -139,8 +208,8 @@ func (s *DeleteService) buildURL() (string, url.Values, error) { if s.timeout != "" { params.Set("timeout", s.timeout) } - if s.version != nil { - params.Set("version", fmt.Sprintf("%v", s.version)) + if v := s.version; v != nil { + params.Set("version", fmt.Sprint(v)) } if s.versionType != "" { params.Set("version_type", s.versionType) @@ -151,6 +220,12 @@ func (s *DeleteService) buildURL() (string, url.Values, error) { if s.parent != "" { params.Set("parent", s.parent) } + if v := s.ifSeqNo; v != nil { + params.Set("if_seq_no", fmt.Sprintf("%d", *v)) + } + if v := s.ifPrimaryTerm; v != nil { + params.Set("if_primary_term", fmt.Sprintf("%d", *v)) + } return path, params, nil } @@ -193,6 +268,7 @@ func (s *DeleteService) Do(ctx context.Context) (*DeleteResponse, error) { Path: path, Params: params, IgnoreErrors: []int{http.StatusNotFound}, + Headers: s.headers, }) if err != nil { return nil, err @@ -221,7 +297,7 @@ type DeleteResponse struct { Id string `json:"_id,omitempty"` Version int64 `json:"_version,omitempty"` Result string `json:"result,omitempty"` - Shards *shardsInfo `json:"_shards,omitempty"` + Shards *ShardsInfo `json:"_shards,omitempty"` SeqNo int64 `json:"_seq_no,omitempty"` PrimaryTerm int64 `json:"_primary_term,omitempty"` Status int `json:"status,omitempty"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/delete_by_query.go b/vendor/github.com/olivere/elastic/v7/delete_by_query.go similarity index 87% rename from vendor/gopkg.in/olivere/elastic.v6/delete_by_query.go rename to vendor/github.com/olivere/elastic/v7/delete_by_query.go index c9e006c..4c98444 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/delete_by_query.go +++ b/vendor/github.com/olivere/elastic/v7/delete_by_query.go @@ -7,16 +7,24 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // DeleteByQueryService deletes documents that match a query. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-delete-by-query.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-delete-by-query.html. type DeleteByQueryService struct { - client *Client + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string query Query @@ -62,7 +70,6 @@ type DeleteByQueryService struct { version *bool waitForActiveShards string waitForCompletion *bool - pretty bool } // NewDeleteByQueryService creates a new DeleteByQueryService. @@ -75,6 +82,46 @@ func NewDeleteByQueryService(client *Client) *DeleteByQueryService { return builder } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *DeleteByQueryService) Pretty(pretty bool) *DeleteByQueryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *DeleteByQueryService) Human(human bool) *DeleteByQueryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *DeleteByQueryService) ErrorTrace(errorTrace bool) *DeleteByQueryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *DeleteByQueryService) FilterPath(filterPath ...string) *DeleteByQueryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *DeleteByQueryService) Header(name string, value string) *DeleteByQueryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *DeleteByQueryService) Headers(headers http.Header) *DeleteByQueryService { + s.headers = headers + return s +} + // Index sets the indices on which to perform the delete operation. func (s *DeleteByQueryService) Index(index ...string) *DeleteByQueryService { s.index = append(s.index, index...) @@ -82,6 +129,9 @@ func (s *DeleteByQueryService) Index(index ...string) *DeleteByQueryService { } // Type limits the delete operation to the given types. +// +// Deprecated: Types are in the process of being removed. Instead of +// using a type, prefer to filter on a field of the document. func (s *DeleteByQueryService) Type(typ ...string) *DeleteByQueryService { s.typ = append(s.typ, typ...) return s @@ -242,7 +292,7 @@ func (s *DeleteByQueryService) Query(query Query) *DeleteByQueryService { // Refresh indicates whether the effected indexes should be refreshed. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *DeleteByQueryService) Refresh(refresh string) *DeleteByQueryService { s.refresh = refresh @@ -303,9 +353,9 @@ func (s *DeleteByQueryService) Size(size int) *DeleteByQueryService { } // Slices represents the number of slices (default: 1). -// It used to be a number, but can be set to "auto" as of 6.3. +// It used to be a number, but can be set to "auto" as of 6.7. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/docs-delete-by-query.html#docs-delete-by-query-automatic-slice +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-delete-by-query.html#docs-delete-by-query-automatic-slice // for details. func (s *DeleteByQueryService) Slices(slices interface{}) *DeleteByQueryService { s.slices = slices @@ -413,12 +463,6 @@ func (s *DeleteByQueryService) WaitForCompletion(waitForCompletion bool) *Delete return s } -// Pretty indents the JSON output from Elasticsearch. -func (s *DeleteByQueryService) Pretty(pretty bool) *DeleteByQueryService { - s.pretty = pretty - return s -} - // Body specifies the body of the request. It overrides data being specified via SearchService. func (s *DeleteByQueryService) Body(body string) *DeleteByQueryService { s.body = body @@ -446,14 +490,26 @@ func (s *DeleteByQueryService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } if len(s.xSource) > 0 { params.Set("_source", strings.Join(s.xSource, ",")) } if len(s.xSourceExclude) > 0 { - params.Set("_source_exclude", strings.Join(s.xSourceExclude, ",")) + params.Set("_source_excludes", strings.Join(s.xSourceExclude, ",")) } if len(s.xSourceInclude) > 0 { - params.Set("_source_include", strings.Join(s.xSourceInclude, ",")) + params.Set("_source_includes", strings.Join(s.xSourceInclude, ",")) } if s.analyzer != "" { params.Set("analyzer", s.analyzer) @@ -569,9 +625,6 @@ func (s *DeleteByQueryService) buildURL() (string, url.Values, error) { if s.requestsPerSecond != nil { params.Set("requests_per_second", fmt.Sprintf("%v", *s.requestsPerSecond)) } - if s.pretty { - params.Set("pretty", fmt.Sprintf("%v", s.pretty)) - } return path, params, nil } @@ -616,10 +669,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -691,16 +745,17 @@ func (s *DeleteByQueryService) DoAsync(ctx context.Context) (*StartTaskResult, e // BulkIndexByScrollResponse is the outcome of executing Do with // DeleteByQueryService and UpdateByQueryService. type BulkIndexByScrollResponse struct { - Took int64 `json:"took"` - SliceId *int64 `json:"slice_id,omitempty"` - TimedOut bool `json:"timed_out"` - Total int64 `json:"total"` - Updated int64 `json:"updated,omitempty"` - Created int64 `json:"created,omitempty"` - Deleted int64 `json:"deleted"` - Batches int64 `json:"batches"` - VersionConflicts int64 `json:"version_conflicts"` - Noops int64 `json:"noops"` + Header http.Header `json:"-"` + Took int64 `json:"took"` + SliceId *int64 `json:"slice_id,omitempty"` + TimedOut bool `json:"timed_out"` + Total int64 `json:"total"` + Updated int64 `json:"updated,omitempty"` + Created int64 `json:"created,omitempty"` + Deleted int64 `json:"deleted"` + Batches int64 `json:"batches"` + VersionConflicts int64 `json:"version_conflicts"` + Noops int64 `json:"noops"` Retries struct { Bulk int64 `json:"bulk"` Search int64 `json:"search"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/doc.go b/vendor/github.com/olivere/elastic/v7/doc.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/doc.go rename to vendor/github.com/olivere/elastic/v7/doc.go diff --git a/vendor/github.com/olivere/elastic/v7/docker-compose.yml b/vendor/github.com/olivere/elastic/v7/docker-compose.yml new file mode 100644 index 0000000..2fd0d98 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/docker-compose.yml @@ -0,0 +1,61 @@ +version: '3' + +services: + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch-oss:7.6.2 + hostname: elasticsearch + environment: + - cluster.name=elasticsearch + - bootstrap.memory_lock=true + - discovery.type=single-node + # - http.publish_host=localhost + # - http.host=0.0.0.0 + # - transport.host=127.0.0.1 + # - network.host=_local_ + - network.publish_host=127.0.0.1 + - logger.org.elasticsearch=warn + - "ES_JAVA_OPTS=-Xms1g -Xmx1g" + ulimits: + nproc: 65536 + nofile: + soft: 65536 + hard: 65536 + memlock: + soft: -1 + hard: -1 + # volumes: + # - ./data/elasticsearch:/usr/share/elasticsearch/data + ports: + - 9200:9200 + platinum: + image: docker.elastic.co/elasticsearch/elasticsearch:7.6.2 + hostname: elasticsearch-platinum + environment: + - cluster.name=platinum + - bootstrap.memory_lock=true + - discovery.type=single-node + - xpack.ilm.enabled=true + - xpack.license.self_generated.type=trial + - xpack.security.enabled=true + - xpack.watcher.enabled=true + # - http.publish_host=localhost + # - http.host=0.0.0.0 + # - transport.host=127.0.0.1 + # - network.host=_local_ + - http.port=9210 + - network.publish_host=127.0.0.1 + - logger.org.elasticsearch=warn + - "ES_JAVA_OPTS=-Xms1g -Xmx1g" + - ELASTIC_PASSWORD=elastic + ulimits: + nproc: 65536 + nofile: + soft: 65536 + hard: 65536 + memlock: + soft: -1 + hard: -1 + # volumes: + # - ./data/elasticsearch-platinum:/usr/share/elasticsearch/data + ports: + - 9210:9210 diff --git a/vendor/github.com/olivere/elastic/v7/docvalue_field.go b/vendor/github.com/olivere/elastic/v7/docvalue_field.go new file mode 100644 index 0000000..e73cd24 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/docvalue_field.go @@ -0,0 +1,42 @@ +// 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 + +// DocvalueField represents a docvalue field, its name and +// its format (optional). +type DocvalueField struct { + Field string + Format string +} + +// Source serializes the DocvalueField into JSON. +func (d DocvalueField) Source() (interface{}, error) { + if d.Format == "" { + return d.Field, nil + } + return map[string]interface{}{ + "field": d.Field, + "format": d.Format, + }, nil +} + +// DocvalueFields is a slice of DocvalueField instances. +type DocvalueFields []DocvalueField + +// Source serializes the DocvalueFields into JSON. +func (d DocvalueFields) Source() (interface{}, error) { + if d == nil { + return nil, nil + } + v := make([]interface{}, 0) + for _, f := range d { + src, err := f.Source() + if err != nil { + return nil, err + } + v = append(v, src) + } + return v, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/errors.go b/vendor/github.com/olivere/elastic/v7/errors.go similarity index 75% rename from vendor/gopkg.in/olivere/elastic.v6/errors.go rename to vendor/github.com/olivere/elastic/v7/errors.go index 2aeff6b..0b51c5e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/errors.go +++ b/vendor/github.com/olivere/elastic/v7/errors.go @@ -82,6 +82,21 @@ type ErrorDetails struct { CausedBy map[string]interface{} `json:"caused_by,omitempty"` RootCause []*ErrorDetails `json:"root_cause,omitempty"` FailedShards []map[string]interface{} `json:"failed_shards,omitempty"` + + // ScriptException adds the information in the following block. + + ScriptStack []string `json:"script_stack,omitempty"` // from ScriptException + Script string `json:"script,omitempty"` // from ScriptException + Lang string `json:"lang,omitempty"` // from ScriptException + Position *ScriptErrorPosition `json:"position,omitempty"` // from ScriptException (7.7+) +} + +// ScriptErrorPosition specifies the position of the error +// in a script. It is used in ErrorDetails for scripting errors. +type ScriptErrorPosition struct { + Offset int `json:"offset"` + Start int `json:"start"` + End int `json:"end"` } // Error returns a string representation of the error. @@ -137,6 +152,14 @@ func IsConflict(err interface{}) bool { return IsStatusCode(err, http.StatusConflict) } +// IsForbidden returns true if the given error indicates that Elasticsearch +// returned HTTP status 403. This happens e.g. due to a missing license. +// The err parameter can be of type *elastic.Error, elastic.Error, +// *http.Response or int (indicating the HTTP status code). +func IsForbidden(err interface{}) bool { + return IsStatusCode(err, http.StatusForbidden) +} + // IsStatusCode returns true if the given error indicates that the Elasticsearch // operation returned the specified HTTP status code. The err parameter can be of // type *http.Response, *Error, Error, or int (indicating the HTTP status code). @@ -156,17 +179,21 @@ func IsStatusCode(err interface{}, code int) bool { // -- General errors -- -// shardsInfo represents information from a shard. -type shardsInfo struct { - Total int `json:"total"` - Successful int `json:"successful"` - Failed int `json:"failed"` +// ShardsInfo represents information from a shard. +type ShardsInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []*ShardFailure `json:"failures,omitempty"` + Skipped int `json:"skipped,omitempty"` } -// shardOperationFailure represents a shard failure. -type shardOperationFailure struct { - Shard int `json:"shard"` - Index string `json:"index"` - Status string `json:"status"` - // "reason" +// ShardFailure represents details about a failure. +type ShardFailure struct { + Index string `json:"_index,omitempty"` + Shard int `json:"_shard,omitempty"` + Node string `json:"_node,omitempty"` + Reason map[string]interface{} `json:"reason,omitempty"` + Status string `json:"status,omitempty"` + Primary bool `json:"primary,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/exists.go b/vendor/github.com/olivere/elastic/v7/exists.go similarity index 65% rename from vendor/gopkg.in/olivere/elastic.v6/exists.go rename to vendor/github.com/olivere/elastic/v7/exists.go index 9031bdd..dbc353a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/exists.go +++ b/vendor/github.com/olivere/elastic/v7/exists.go @@ -9,17 +9,24 @@ import ( "fmt" "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ExistsService checks for the existence of a document using HEAD. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-get.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-get.html // for details. type ExistsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string index string typ string @@ -34,9 +41,50 @@ type ExistsService struct { func NewExistsService(client *Client) *ExistsService { return &ExistsService{ client: client, + typ: "_doc", } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ExistsService) Pretty(pretty bool) *ExistsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ExistsService) Human(human bool) *ExistsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ExistsService) ErrorTrace(errorTrace bool) *ExistsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ExistsService) FilterPath(filterPath ...string) *ExistsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ExistsService) Header(name string, value string) *ExistsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ExistsService) Headers(headers http.Header) *ExistsService { + s.headers = headers + return s +} + // Id is the document ID. func (s *ExistsService) Id(id string) *ExistsService { s.id = id @@ -70,7 +118,7 @@ func (s *ExistsService) Realtime(realtime bool) *ExistsService { // Refresh the shard containing the document before performing the operation. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *ExistsService) Refresh(refresh string) *ExistsService { s.refresh = refresh @@ -89,12 +137,6 @@ func (s *ExistsService) Parent(parent string) *ExistsService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ExistsService) Pretty(pretty bool) *ExistsService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *ExistsService) buildURL() (string, url.Values, error) { // Build URL @@ -109,11 +151,20 @@ func (s *ExistsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.realtime != nil { - params.Set("realtime", fmt.Sprintf("%v", *s.realtime)) + params.Set("realtime", fmt.Sprint(*s.realtime)) } if s.refresh != "" { params.Set("refresh", s.refresh) @@ -167,6 +218,7 @@ func (s *ExistsService) Do(ctx context.Context) (bool, error) { Path: path, Params: params, IgnoreErrors: []int{404}, + Headers: s.headers, }) if err != nil { return false, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/explain.go b/vendor/github.com/olivere/elastic/v7/explain.go similarity index 76% rename from vendor/gopkg.in/olivere/elastic.v6/explain.go rename to vendor/github.com/olivere/elastic/v7/explain.go index 52b8d37..dc8795e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/explain.go +++ b/vendor/github.com/olivere/elastic/v7/explain.go @@ -7,18 +7,25 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ExplainService computes a score explanation for a query and // a specific document. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-explain.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-explain.html. type ExplainService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string index string typ string @@ -45,6 +52,7 @@ type ExplainService struct { func NewExplainService(client *Client) *ExplainService { return &ExplainService{ client: client, + typ: "_doc", xSource: make([]string, 0), xSourceExclude: make([]string, 0), fields: make([]string, 0), @@ -52,6 +60,46 @@ func NewExplainService(client *Client) *ExplainService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ExplainService) Pretty(pretty bool) *ExplainService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ExplainService) Human(human bool) *ExplainService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ExplainService) ErrorTrace(errorTrace bool) *ExplainService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ExplainService) FilterPath(filterPath ...string) *ExplainService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ExplainService) Header(name string, value string) *ExplainService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ExplainService) Headers(headers http.Header) *ExplainService { + s.headers = headers + return s +} + // Id is the document ID. func (s *ExplainService) Id(id string) *ExplainService { s.id = id @@ -65,6 +113,8 @@ func (s *ExplainService) Index(index string) *ExplainService { } // Type is the type of the document. +// +// Deprecated: Types are in the process of being removed. func (s *ExplainService) Type(typ string) *ExplainService { s.typ = typ return s @@ -162,12 +212,6 @@ func (s *ExplainService) XSource(xSource ...string) *ExplainService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ExplainService) Pretty(pretty bool) *ExplainService { - s.pretty = pretty - return s -} - // Query sets a query definition using the Query DSL. func (s *ExplainService) Query(query Query) *ExplainService { src, err := query.Source() @@ -196,19 +240,38 @@ func (s *ExplainService) BodyString(body string) *ExplainService { // buildURL builds the URL for the operation. func (s *ExplainService) buildURL() (string, url.Values, error) { // Build URL - path, err := uritemplates.Expand("/{index}/{type}/{id}/_explain", map[string]string{ - "id": s.id, - "index": s.index, - "type": s.typ, - }) + var path string + var err error + + if s.typ == "" || s.typ == "_doc" { + path, err = uritemplates.Expand("/{index}/_explain/{id}", map[string]string{ + "id": s.id, + "index": s.index, + }) + } else { + path, err = uritemplates.Expand("/{index}/{type}/{id}/_explain", map[string]string{ + "id": s.id, + "index": s.index, + "type": s.typ, + }) + } if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if len(s.xSource) > 0 { params.Set("_source", strings.Join(s.xSource, ",")) @@ -226,7 +289,7 @@ func (s *ExplainService) buildURL() (string, url.Values, error) { params.Set("source", s.source) } if len(s.xSourceExclude) > 0 { - params.Set("_source_exclude", strings.Join(s.xSourceExclude, ",")) + params.Set("_source_excludes", strings.Join(s.xSourceExclude, ",")) } if s.lenient != nil { params.Set("lenient", fmt.Sprintf("%v", *s.lenient)) @@ -244,7 +307,7 @@ func (s *ExplainService) buildURL() (string, url.Values, error) { params.Set("lowercase_expanded_terms", fmt.Sprintf("%v", *s.lowercaseExpandedTerms)) } if len(s.xSourceInclude) > 0 { - params.Set("_source_include", strings.Join(s.xSourceInclude, ",")) + params.Set("_source_includes", strings.Join(s.xSourceInclude, ",")) } if s.analyzeWildcard != nil { params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard)) @@ -299,10 +362,11 @@ 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, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/fetch_source_context.go b/vendor/github.com/olivere/elastic/v7/fetch_source_context.go similarity index 90% rename from vendor/gopkg.in/olivere/elastic.v6/fetch_source_context.go rename to vendor/github.com/olivere/elastic/v7/fetch_source_context.go index 91488ba..7a4a769 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/fetch_source_context.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-request-source-filtering.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-source-filtering.html // for details. type FetchSourceContext struct { fetchSource bool @@ -78,10 +78,10 @@ func (fsc *FetchSourceContext) Query() url.Values { params := url.Values{} if fsc.fetchSource { if len(fsc.includes) > 0 { - params.Add("_source_include", strings.Join(fsc.includes, ",")) + params.Add("_source_includes", strings.Join(fsc.includes, ",")) } if len(fsc.excludes) > 0 { - params.Add("_source_exclude", strings.Join(fsc.excludes, ",")) + params.Add("_source_excludes", strings.Join(fsc.excludes, ",")) } } else { params.Add("_source", "false") diff --git a/vendor/gopkg.in/olivere/elastic.v6/field_caps.go b/vendor/github.com/olivere/elastic/v7/field_caps.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/field_caps.go rename to vendor/github.com/olivere/elastic/v7/field_caps.go index a4b6049..b84a1f1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/field_caps.go +++ b/vendor/github.com/olivere/elastic/v7/field_caps.go @@ -11,16 +11,22 @@ import ( "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // FieldCapsService allows retrieving the capabilities of fields among multiple indices. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-field-caps.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-field-caps.html // for details type FieldCapsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string allowNoIndices *bool expandWildcards string @@ -37,6 +43,46 @@ func NewFieldCapsService(client *Client) *FieldCapsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *FieldCapsService) Pretty(pretty bool) *FieldCapsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *FieldCapsService) Human(human bool) *FieldCapsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *FieldCapsService) ErrorTrace(errorTrace bool) *FieldCapsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *FieldCapsService) FilterPath(filterPath ...string) *FieldCapsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *FieldCapsService) Header(name string, value string) *FieldCapsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *FieldCapsService) Headers(headers http.Header) *FieldCapsService { + s.headers = headers + return s +} + // Index is a list of index names; use `_all` or empty string to perform // the operation on all indices. func (s *FieldCapsService) Index(index ...string) *FieldCapsService { @@ -71,12 +117,6 @@ func (s *FieldCapsService) IgnoreUnavailable(ignoreUnavailable bool) *FieldCapsS return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *FieldCapsService) Pretty(pretty bool) *FieldCapsService { - 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 *FieldCapsService) BodyJson(body interface{}) *FieldCapsService { s.bodyJson = body @@ -107,8 +147,17 @@ func (s *FieldCapsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -158,6 +207,7 @@ func (s *FieldCapsService) Do(ctx context.Context) (*FieldCapsResponse, error) { Params: params, Body: body, IgnoreErrors: []int{http.StatusNotFound}, + Headers: s.headers, }) if err != nil { return nil, err @@ -188,9 +238,14 @@ type FieldCapsRequest struct { // FieldCapsResponse contains field capabilities. type FieldCapsResponse struct { - Fields map[string]FieldCaps `json:"fields,omitempty"` + Indices []string `json:"indices,omitempty"` // list of index names + Fields map[string]FieldCapsType `json:"fields,omitempty"` // Name -> type -> caps } +// FieldCapsType represents a mapping from type (e.g. keyword) +// to capabilities. +type FieldCapsType map[string]FieldCaps // type -> caps + // FieldCaps contains capabilities of an individual field. type FieldCaps struct { Type string `json:"type"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/geo_point.go b/vendor/github.com/olivere/elastic/v7/geo_point.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/geo_point.go rename to vendor/github.com/olivere/elastic/v7/geo_point.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/get.go b/vendor/github.com/olivere/elastic/v7/get.go similarity index 66% rename from vendor/gopkg.in/olivere/elastic.v6/get.go rename to vendor/github.com/olivere/elastic/v7/get.go index 8c26455..769389b 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/get.go +++ b/vendor/github.com/olivere/elastic/v7/get.go @@ -8,20 +8,27 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/docs-get.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-get.html // for details. type GetService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index string typ string id string @@ -41,8 +48,48 @@ type GetService struct { func NewGetService(client *Client) *GetService { return &GetService{ client: client, - typ: "_all", + typ: "_doc", + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *GetService) Pretty(pretty bool) *GetService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *GetService) Human(human bool) *GetService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *GetService) ErrorTrace(errorTrace bool) *GetService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *GetService) FilterPath(filterPath ...string) *GetService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *GetService) Header(name string, value string) *GetService { + if s.headers == nil { + s.headers = http.Header{} } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *GetService) Headers(headers http.Header) *GetService { + s.headers = headers + return s } // Index is the name of the index. @@ -51,8 +98,9 @@ func (s *GetService) Index(index string) *GetService { return s } -// Type is the type of the document (use `_all` to fetch the first document -// matching the ID across all types). +// Type is the type of the document +// +// Deprecated: Types are in the process of being removed. func (s *GetService) Type(typ string) *GetService { s.typ = typ return s @@ -104,7 +152,7 @@ func (s *GetService) FetchSourceContext(fetchSourceContext *FetchSourceContext) // Refresh the shard containing the document before performing the operation. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *GetService) Refresh(refresh string) *GetService { s.refresh = refresh @@ -136,12 +184,6 @@ func (s *GetService) IgnoreErrorsOnGeneratedFields(ignore bool) *GetService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *GetService) Pretty(pretty bool) *GetService { - s.pretty = pretty - return s -} - // Validate checks if the operation is valid. func (s *GetService) Validate() error { var invalid []string @@ -174,8 +216,17 @@ func (s *GetService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.routing != "" { params.Set("routing", s.routing) @@ -227,9 +278,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -247,16 +299,18 @@ func (s *GetService) Do(ctx context.Context) (*GetResult, error) { // GetResult is the outcome of GetService.Do. type GetResult struct { - Index string `json:"_index"` // index meta field - Type string `json:"_type"` // type meta field - Id string `json:"_id"` // id meta field - Uid string `json:"_uid"` // uid meta field (see MapperService.java for all meta fields) - Routing string `json:"_routing"` // routing meta field - Parent string `json:"_parent"` // parent meta field - Version *int64 `json:"_version"` // version number, when Version is set to true in SearchService - Source *json.RawMessage `json:"_source,omitempty"` - Found bool `json:"found,omitempty"` - Fields map[string]interface{} `json:"fields,omitempty"` + Index string `json:"_index"` // index meta field + Type string `json:"_type"` // type meta field + Id string `json:"_id"` // id meta field + Uid string `json:"_uid"` // uid meta field (see MapperService.java for all meta fields) + Routing string `json:"_routing"` // routing meta field + Parent string `json:"_parent"` // parent meta field + Version *int64 `json:"_version"` // version number, when Version is set to true in SearchService + SeqNo *int64 `json:"_seq_no"` + PrimaryTerm *int64 `json:"_primary_term"` + Source json.RawMessage `json:"_source,omitempty"` + Found bool `json:"found,omitempty"` + Fields map[string]interface{} `json:"fields,omitempty"` //Error string `json:"error,omitempty"` // used only in MultiGet // TODO double-check that MultiGet now returns details error information Error *ErrorDetails `json:"error,omitempty"` // only used in MultiGet diff --git a/vendor/github.com/olivere/elastic/v7/go.mod b/vendor/github.com/olivere/elastic/v7/go.mod new file mode 100644 index 0000000..61cca83 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/go.mod @@ -0,0 +1,14 @@ +module github.com/olivere/elastic/v7 + +go 1.14 + +require ( + github.com/aws/aws-sdk-go v1.30.7 + github.com/fortytw2/leaktest v1.3.0 + github.com/google/go-cmp v0.4.0 + github.com/mailru/easyjson v0.7.1 + github.com/opentracing/opentracing-go v1.1.0 + github.com/pkg/errors v0.9.1 + github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9 + go.opencensus.io v0.22.3 +) diff --git a/vendor/gopkg.in/olivere/elastic.v6/highlight.go b/vendor/github.com/olivere/elastic/v7/highlight.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/highlight.go rename to vendor/github.com/olivere/elastic/v7/highlight.go index ed024e4..49e1b4d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/highlight.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-request-highlighting.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-highlighting.html type Highlight struct { fields []*HighlighterField tagsSchema *string @@ -125,7 +125,7 @@ func (hl *Highlight) Fragmenter(fragmenter string) *Highlight { return hl } -func (hl *Highlight) HighlighQuery(highlightQuery Query) *Highlight { +func (hl *Highlight) HighlightQuery(highlightQuery Query) *Highlight { hl.highlightQuery = highlightQuery return hl } @@ -238,7 +238,7 @@ func (hl *Highlight) Source() (interface{}, error) { source["fields"] = fields } else { // Use a map for the fields - fields := make(map[string]interface{}, 0) + fields := make(map[string]interface{}) for _, field := range hl.fields { src, err := field.Source() if err != nil { diff --git a/vendor/gopkg.in/olivere/elastic.v6/index.go b/vendor/github.com/olivere/elastic/v7/index.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/index.go rename to vendor/github.com/olivere/elastic/v7/index.go index 807dd27..2e3d66f 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/index.go +++ b/vendor/github.com/olivere/elastic/v7/index.go @@ -7,19 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/docs-index_.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-index_.html // for details. type IndexService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string index string typ string @@ -34,6 +42,8 @@ type IndexService struct { refresh string waitForActiveShards string pipeline string + ifSeqNo *int64 + ifPrimaryTerm *int64 bodyJson interface{} bodyString string } @@ -42,7 +52,48 @@ type IndexService struct { func NewIndexService(client *Client) *IndexService { return &IndexService{ client: client, + typ: "_doc", + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndexService) Pretty(pretty bool) *IndexService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndexService) Human(human bool) *IndexService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndexService) ErrorTrace(errorTrace bool) *IndexService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndexService) FilterPath(filterPath ...string) *IndexService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndexService) Header(name string, value string) *IndexService { + if s.headers == nil { + s.headers = http.Header{} } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndexService) Headers(headers http.Header) *IndexService { + s.headers = headers + return s } // Id is the document ID. @@ -58,6 +109,8 @@ func (s *IndexService) Index(index string) *IndexService { } // Type is the type of the document. +// +// Deprecated: Types are in the process of being removed. func (s *IndexService) Type(typ string) *IndexService { s.typ = typ return s @@ -81,7 +134,7 @@ func (s *IndexService) Pipeline(pipeline string) *IndexService { // Refresh the index after performing the operation. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *IndexService) Refresh(refresh string) *IndexService { s.refresh = refresh @@ -142,9 +195,17 @@ func (s *IndexService) VersionType(versionType string) *IndexService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndexService) Pretty(pretty bool) *IndexService { - s.pretty = pretty +// IfSeqNo indicates to only perform the index operation if the last +// operation that has changed the document has the specified sequence number. +func (s *IndexService) IfSeqNo(seqNo int64) *IndexService { + s.ifSeqNo = &seqNo + return s +} + +// IfPrimaryTerm indicates to only perform the index operation if the +// last operation that has changed the document has the specified primary term. +func (s *IndexService) IfPrimaryTerm(primaryTerm int64) *IndexService { + s.ifPrimaryTerm = &primaryTerm return s } @@ -175,7 +236,7 @@ func (s *IndexService) buildURL() (string, string, url.Values, error) { }) } else { // Automatic ID generation - // See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-index_.html#index-creation + // See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-index_.html#index-creation method = "POST" path, err = uritemplates.Expand("/{index}/{type}/", map[string]string{ "index": s.index, @@ -188,8 +249,17 @@ func (s *IndexService) buildURL() (string, string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.waitForActiveShards != "" { params.Set("wait_for_active_shards", s.waitForActiveShards) @@ -224,6 +294,12 @@ func (s *IndexService) buildURL() (string, string, url.Values, error) { if s.versionType != "" { params.Set("version_type", s.versionType) } + if v := s.ifSeqNo; v != nil { + params.Set("if_seq_no", fmt.Sprintf("%d", *v)) + } + if v := s.ifPrimaryTerm; v != nil { + params.Set("if_primary_term", fmt.Sprintf("%d", *v)) + } return method, path, params, nil } @@ -268,10 +344,11 @@ 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, + Method: method, + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -292,7 +369,7 @@ type IndexResponse struct { Id string `json:"_id,omitempty"` Version int64 `json:"_version,omitempty"` Result string `json:"result,omitempty"` - Shards *shardsInfo `json:"_shards,omitempty"` + Shards *ShardsInfo `json:"_shards,omitempty"` SeqNo int64 `json:"_seq_no,omitempty"` PrimaryTerm int64 `json:"_primary_term,omitempty"` Status int `json:"status,omitempty"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_analyze.go b/vendor/github.com/olivere/elastic/v7/indices_analyze.go similarity index 63% rename from vendor/gopkg.in/olivere/elastic.v6/indices_analyze.go rename to vendor/github.com/olivere/elastic/v7/indices_analyze.go index e57c381..3f0c282 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_analyze.go +++ b/vendor/github.com/olivere/elastic/v7/indices_analyze.go @@ -7,19 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/indices-analyze.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-analyze.html // for detail. type IndicesAnalyzeService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index string request *IndicesAnalyzeRequest format string @@ -36,6 +44,46 @@ func NewIndicesAnalyzeService(client *Client) *IndicesAnalyzeService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesAnalyzeService) Pretty(pretty bool) *IndicesAnalyzeService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesAnalyzeService) Human(human bool) *IndicesAnalyzeService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesAnalyzeService) ErrorTrace(errorTrace bool) *IndicesAnalyzeService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesAnalyzeService) FilterPath(filterPath ...string) *IndicesAnalyzeService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesAnalyzeService) Header(name string, value string) *IndicesAnalyzeService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesAnalyzeService) Headers(headers http.Header) *IndicesAnalyzeService { + s.headers = headers + return s +} + // Index is the name of the index to scope the operation. func (s *IndicesAnalyzeService) Index(index string) *IndicesAnalyzeService { s.index = index @@ -114,12 +162,6 @@ func (s *IndicesAnalyzeService) Tokenizer(tokenizer string) *IndicesAnalyzeServi return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesAnalyzeService) Pretty(pretty bool) *IndicesAnalyzeService { - s.pretty = pretty - return s -} - // BodyJson is the text on which the analysis should be performed. func (s *IndicesAnalyzeService) BodyJson(body interface{}) *IndicesAnalyzeService { s.bodyJson = body @@ -151,8 +193,17 @@ func (s *IndicesAnalyzeService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.format != "" { params.Set("format", s.format) @@ -185,15 +236,16 @@ 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.2/indices-analyze.html + // See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-analyze.html body = s.request } res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -233,52 +285,36 @@ type IndicesAnalyzeRequest struct { } type IndicesAnalyzeResponse struct { - Tokens []IndicesAnalyzeResponseToken `json:"tokens"` // json part for normal message - Detail IndicesAnalyzeResponseDetail `json:"detail"` // json part for verbose message of explain request + Tokens []AnalyzeToken `json:"tokens"` // json part for normal message + Detail IndicesAnalyzeResponseDetail `json:"detail"` // json part for verbose message of explain request +} + +type AnalyzeTokenList struct { + Name string `json:"name"` + Tokens []AnalyzeToken `json:"tokens,omitempty"` +} + +type AnalyzeToken struct { + Token string `json:"token"` + Type string `json:"type"` // e.g. "<ALPHANUM>" + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Bytes string `json:"bytes"` // e.g. "[67 75 79]" + Position int `json:"position"` + PositionLength int `json:"positionLength"` // seems to be wrong in 7.2+ (no snake_case), see https://github.com/elastic/elasticsearch/blob/7.2/server/src/main/java/org/elasticsearch/action/admin/indices/analyze/AnalyzeResponse.java + TermFrequency int `json:"termFrequency"` + Keyword bool `json:"keyword"` } -type IndicesAnalyzeResponseToken struct { - Token string `json:"token"` - StartOffset int `json:"start_offset"` - EndOffset int `json:"end_offset"` - Type string `json:"type"` - Position int `json:"position"` +type CharFilteredText struct { + Name string `json:"name"` + FilteredText []string `json:"filtered_text"` } type IndicesAnalyzeResponseDetail struct { - CustomAnalyzer bool `json:"custom_analyzer"` - Charfilters []interface{} `json:"charfilters"` - Analyzer struct { - Name string `json:"name"` - Tokens []struct { - Token string `json:"token"` - StartOffset int `json:"start_offset"` - EndOffset int `json:"end_offset"` - Type string `json:"type"` - Position int `json:"position"` - Bytes string `json:"bytes"` - PositionLength int `json:"positionLength"` - } `json:"tokens"` - } `json:"analyzer"` - Tokenizer struct { - Name string `json:"name"` - Tokens []struct { - Token string `json:"token"` - StartOffset int `json:"start_offset"` - EndOffset int `json:"end_offset"` - Type string `json:"type"` - Position int `json:"position"` - } `json:"tokens"` - } `json:"tokenizer"` - Tokenfilters []struct { - Name string `json:"name"` - Tokens []struct { - Token string `json:"token"` - StartOffset int `json:"start_offset"` - EndOffset int `json:"end_offset"` - Type string `json:"type"` - Position int `json:"position"` - Keyword bool `json:"keyword"` - } `json:"tokens"` - } `json:"tokenfilters"` + CustomAnalyzer bool `json:"custom_analyzer"` + Analyzer *AnalyzeTokenList `json:"analyzer,omitempty"` + Charfilters []*CharFilteredText `json:"charfilters,omitempty"` + Tokenizer *AnalyzeTokenList `json:"tokenizer,omitempty"` + TokenFilters []*AnalyzeTokenList `json:"tokenfilters,omitempty"` } diff --git a/vendor/github.com/olivere/elastic/v7/indices_clear_cache.go b/vendor/github.com/olivere/elastic/v7/indices_clear_cache.go new file mode 100644 index 0000000..7a2d9f7 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_clear_cache.go @@ -0,0 +1,240 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesClearCacheService allows to clear either all caches or specific cached associated +// with one or more indices. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.6/indices-clearcache.html +// for details. +type IndicesClearCacheService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index []string + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string + fieldData *bool + fields string + query *bool + request *bool +} + +// NewIndicesClearCacheService initializes a new instance of +// IndicesClearCacheService. +func NewIndicesClearCacheService(client *Client) *IndicesClearCacheService { + return &IndicesClearCacheService{client: client} +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesClearCacheService) Pretty(pretty bool) *IndicesClearCacheService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesClearCacheService) Human(human bool) *IndicesClearCacheService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesClearCacheService) ErrorTrace(errorTrace bool) *IndicesClearCacheService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesClearCacheService) FilterPath(filterPath ...string) *IndicesClearCacheService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesClearCacheService) Header(name string, value string) *IndicesClearCacheService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesClearCacheService) Headers(headers http.Header) *IndicesClearCacheService { + s.headers = headers + return s +} + +// Index is the comma-separated list or wildcard expression of index names used to clear cache. +func (s *IndicesClearCacheService) Index(indices ...string) *IndicesClearCacheService { + s.index = append(s.index, indices...) + return s +} + +// IgnoreUnavailable indicates whether specified concrete indices should be +// ignored when unavailable (missing or closed). +func (s *IndicesClearCacheService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesClearCacheService { + 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 *IndicesClearCacheService) AllowNoIndices(allowNoIndices bool) *IndicesClearCacheService { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards indicates whether to expand wildcard expression to +// concrete indices that are open, closed or both. +func (s *IndicesClearCacheService) ExpandWildcards(expandWildcards string) *IndicesClearCacheService { + s.expandWildcards = expandWildcards + return s +} + +// FieldData indicates whether to clear the fields cache. +// Use the fields parameter to clear the cache of specific fields only. +func (s *IndicesClearCacheService) FieldData(fieldData bool) *IndicesClearCacheService { + s.fieldData = &fieldData + return s +} + +// Fields indicates comma-separated list of field names used to limit the fielddata parameter. +// Defaults to all fields. +func (s *IndicesClearCacheService) Fields(fields string) *IndicesClearCacheService { + s.fields = fields + return s +} + +// Query indicates whether to clear only query cache. +func (s *IndicesClearCacheService) Query(queryCache bool) *IndicesClearCacheService { + s.query = &queryCache + return s +} + +// Request indicates whether to clear only request cache. +func (s *IndicesClearCacheService) Request(requestCache bool) *IndicesClearCacheService { + s.request = &requestCache + return s +} + +// buildURL builds the URL for the operation. +func (s *IndicesClearCacheService) buildURL() (string, url.Values, error) { + // Build URL + var path string + var err error + + if len(s.index) > 0 { + path, err = uritemplates.Expand("/{index}/_cache/clear", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else { + path = "/_cache/clear" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.allowNoIndices; v != nil { + params.Set("allow_no_indices", fmt.Sprint(*v)) + } + if v := s.expandWildcards; v != "" { + params.Set("expand_wildcards", v) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) + } + if len(s.index) > 0 { + params.Set("index", fmt.Sprintf("%v", s.index)) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("fielddata", fmt.Sprint(*v)) + } + if len(s.fields) > 0 { + params.Set("fields", fmt.Sprintf("%v", s.fields)) + } + if v := s.query; v != nil { + params.Set("query", fmt.Sprint(*v)) + } + if s.request != nil { + params.Set("request", fmt.Sprintf("%v", *s.request)) + } + + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *IndicesClearCacheService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *IndicesClearCacheService) Do(ctx context.Context) (*IndicesClearCacheResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(IndicesClearCacheResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// IndicesClearCacheResponse is the response of IndicesClearCacheService.Do. +type IndicesClearCacheResponse struct { + Shards *ShardsInfo `json:"_shards"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_close.go b/vendor/github.com/olivere/elastic/v7/indices_close.go similarity index 67% rename from vendor/gopkg.in/olivere/elastic.v6/indices_close.go rename to vendor/github.com/olivere/elastic/v7/indices_close.go index e6a4127..36edd60 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_close.go +++ b/vendor/github.com/olivere/elastic/v7/indices_close.go @@ -7,18 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesCloseService closes an index. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-open-close.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-open-close.html // for details. type IndicesCloseService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index string timeout string masterTimeout string @@ -32,6 +40,46 @@ func NewIndicesCloseService(client *Client) *IndicesCloseService { return &IndicesCloseService{client: client} } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesCloseService) Pretty(pretty bool) *IndicesCloseService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesCloseService) Human(human bool) *IndicesCloseService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesCloseService) ErrorTrace(errorTrace bool) *IndicesCloseService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesCloseService) FilterPath(filterPath ...string) *IndicesCloseService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesCloseService) Header(name string, value string) *IndicesCloseService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesCloseService) Headers(headers http.Header) *IndicesCloseService { + s.headers = headers + return s +} + // Index is the name of the index to close. func (s *IndicesCloseService) Index(index string) *IndicesCloseService { s.index = index @@ -71,12 +119,6 @@ func (s *IndicesCloseService) ExpandWildcards(expandWildcards string) *IndicesCl return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesCloseService) Pretty(pretty bool) *IndicesCloseService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesCloseService) buildURL() (string, url.Values, error) { // Build URL @@ -89,6 +131,18 @@ func (s *IndicesCloseService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) } @@ -135,9 +189,10 @@ 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, + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/indices_create.go b/vendor/github.com/olivere/elastic/v7/indices_create.go new file mode 100644 index 0000000..4bcd77b --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_create.go @@ -0,0 +1,189 @@ +// 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" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesCreateService creates a new index. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-create-index.html +// for details. +type IndicesCreateService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index string + timeout string + masterTimeout string + bodyJson interface{} + bodyString string +} + +// NewIndicesCreateService returns a new IndicesCreateService. +func NewIndicesCreateService(client *Client) *IndicesCreateService { + return &IndicesCreateService{client: client} +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesCreateService) Pretty(pretty bool) *IndicesCreateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesCreateService) Human(human bool) *IndicesCreateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesCreateService) ErrorTrace(errorTrace bool) *IndicesCreateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesCreateService) FilterPath(filterPath ...string) *IndicesCreateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesCreateService) Header(name string, value string) *IndicesCreateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesCreateService) Headers(headers http.Header) *IndicesCreateService { + s.headers = headers + return s +} + +// Index is the name of the index to create. +func (s *IndicesCreateService) Index(index string) *IndicesCreateService { + s.index = index + return s +} + +// Timeout the explicit operation timeout, e.g. "5s". +func (s *IndicesCreateService) Timeout(timeout string) *IndicesCreateService { + s.timeout = timeout + return s +} + +// MasterTimeout specifies the timeout for connection to master. +func (s *IndicesCreateService) MasterTimeout(masterTimeout string) *IndicesCreateService { + s.masterTimeout = masterTimeout + return s +} + +// Body specifies the configuration of the index as a string. +// It is an alias for BodyString. +func (s *IndicesCreateService) Body(body string) *IndicesCreateService { + s.bodyString = body + return s +} + +// BodyString specifies the configuration of the index as a string. +func (s *IndicesCreateService) BodyString(body string) *IndicesCreateService { + s.bodyString = body + return s +} + +// BodyJson specifies the configuration of the index. The interface{} will +// be serializes as a JSON document, so use a map[string]interface{}. +func (s *IndicesCreateService) BodyJson(body interface{}) *IndicesCreateService { + s.bodyJson = body + return s +} + +// Do executes the operation. +func (s *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, error) { + if s.index == "" { + return nil, errors.New("missing index name") + } + + // Build url + path, err := uritemplates.Expand("/{index}", map[string]string{ + "index": s.index, + }) + if err != nil { + return nil, err + } + + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + + // Setup HTTP request body + var body interface{} + if s.bodyJson != nil { + body = s.bodyJson + } else { + body = s.bodyString + } + + // Get response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + ret := new(IndicesCreateResult) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// -- Result of a create index request. + +// 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"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_delete.go b/vendor/github.com/olivere/elastic/v7/indices_delete.go similarity index 59% rename from vendor/gopkg.in/olivere/elastic.v6/indices_delete.go rename to vendor/github.com/olivere/elastic/v7/indices_delete.go index 59567e2..cdf27a5 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_delete.go +++ b/vendor/github.com/olivere/elastic/v7/indices_delete.go @@ -7,19 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesDeleteService allows to delete existing indices. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-delete-index.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-delete-index.html // for details. type IndicesDeleteService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string timeout string masterTimeout string @@ -33,6 +40,46 @@ func NewIndicesDeleteService(client *Client) *IndicesDeleteService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesDeleteService) Pretty(pretty bool) *IndicesDeleteService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesDeleteService) Human(human bool) *IndicesDeleteService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesDeleteService) ErrorTrace(errorTrace bool) *IndicesDeleteService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesDeleteService) FilterPath(filterPath ...string) *IndicesDeleteService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesDeleteService) Header(name string, value string) *IndicesDeleteService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesDeleteService) Headers(headers http.Header) *IndicesDeleteService { + s.headers = headers + return s +} + // Index adds the list of indices to delete. // Use `_all` or `*` string to delete all indices. func (s *IndicesDeleteService) Index(index []string) *IndicesDeleteService { @@ -52,12 +99,6 @@ func (s *IndicesDeleteService) MasterTimeout(masterTimeout string) *IndicesDelet return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesDeleteService) Pretty(pretty bool) *IndicesDeleteService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesDeleteService) buildURL() (string, url.Values, error) { // Build URL @@ -70,8 +111,17 @@ func (s *IndicesDeleteService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.timeout != "" { params.Set("timeout", s.timeout) @@ -109,9 +159,10 @@ func (s *IndicesDeleteService) Do(ctx context.Context) (*IndicesDeleteResponse, // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "DELETE", - Path: path, - Params: params, + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_delete_template.go b/vendor/github.com/olivere/elastic/v7/indices_delete_template.go similarity index 58% rename from vendor/gopkg.in/olivere/elastic.v6/indices_delete_template.go rename to vendor/github.com/olivere/elastic/v7/indices_delete_template.go index 2a4c466..e1ed3e6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_delete_template.go +++ b/vendor/github.com/olivere/elastic/v7/indices_delete_template.go @@ -7,16 +7,24 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesDeleteTemplateService deletes index templates. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-templates.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-templates.html. type IndicesDeleteTemplateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + name string timeout string masterTimeout string @@ -29,6 +37,46 @@ func NewIndicesDeleteTemplateService(client *Client) *IndicesDeleteTemplateServi } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesDeleteTemplateService) Pretty(pretty bool) *IndicesDeleteTemplateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesDeleteTemplateService) Human(human bool) *IndicesDeleteTemplateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesDeleteTemplateService) ErrorTrace(errorTrace bool) *IndicesDeleteTemplateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesDeleteTemplateService) FilterPath(filterPath ...string) *IndicesDeleteTemplateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesDeleteTemplateService) Header(name string, value string) *IndicesDeleteTemplateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesDeleteTemplateService) Headers(headers http.Header) *IndicesDeleteTemplateService { + s.headers = headers + return s +} + // Name is the name of the template. func (s *IndicesDeleteTemplateService) Name(name string) *IndicesDeleteTemplateService { s.name = name @@ -47,12 +95,6 @@ func (s *IndicesDeleteTemplateService) MasterTimeout(masterTimeout string) *Indi return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesDeleteTemplateService) Pretty(pretty bool) *IndicesDeleteTemplateService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesDeleteTemplateService) buildURL() (string, url.Values, error) { // Build URL @@ -65,8 +107,17 @@ func (s *IndicesDeleteTemplateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.timeout != "" { params.Set("timeout", s.timeout) @@ -104,9 +155,10 @@ func (s *IndicesDeleteTemplateService) Do(ctx context.Context) (*IndicesDeleteTe // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "DELETE", - Path: path, - Params: params, + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_exists.go b/vendor/github.com/olivere/elastic/v7/indices_exists.go similarity index 66% rename from vendor/gopkg.in/olivere/elastic.v6/indices_exists.go rename to vendor/github.com/olivere/elastic/v7/indices_exists.go index 737c31c..a813f56 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_exists.go +++ b/vendor/github.com/olivere/elastic/v7/indices_exists.go @@ -11,16 +11,22 @@ import ( "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesExistsService checks if an index or indices exist or not. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-exists.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-exists.html // for details. type IndicesExistsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string ignoreUnavailable *bool allowNoIndices *bool @@ -36,6 +42,46 @@ func NewIndicesExistsService(client *Client) *IndicesExistsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesExistsService) Pretty(pretty bool) *IndicesExistsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesExistsService) Human(human bool) *IndicesExistsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesExistsService) ErrorTrace(errorTrace bool) *IndicesExistsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesExistsService) FilterPath(filterPath ...string) *IndicesExistsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesExistsService) Header(name string, value string) *IndicesExistsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesExistsService) Headers(headers http.Header) *IndicesExistsService { + s.headers = headers + return s +} + // Index is a list of one or more indices to check. func (s *IndicesExistsService) Index(index []string) *IndicesExistsService { s.index = index @@ -71,12 +117,6 @@ func (s *IndicesExistsService) IgnoreUnavailable(ignoreUnavailable bool) *Indice return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesExistsService) Pretty(pretty bool) *IndicesExistsService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesExistsService) buildURL() (string, url.Values, error) { // Build URL @@ -89,8 +129,17 @@ func (s *IndicesExistsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.local != nil { params.Set("local", fmt.Sprintf("%v", *s.local)) @@ -132,12 +181,12 @@ func (s *IndicesExistsService) Do(ctx context.Context) (bool, error) { return false, err } - // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ Method: "HEAD", Path: path, Params: params, IgnoreErrors: []int{404}, + Headers: s.headers, }) if err != nil { return false, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_exists_template.go b/vendor/github.com/olivere/elastic/v7/indices_exists_template.go similarity index 56% rename from vendor/gopkg.in/olivere/elastic.v6/indices_exists_template.go rename to vendor/github.com/olivere/elastic/v7/indices_exists_template.go index 40b06e8..c5c9bbd 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_exists_template.go +++ b/vendor/github.com/olivere/elastic/v7/indices_exists_template.go @@ -9,18 +9,25 @@ import ( "fmt" "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesExistsTemplateService checks if a given template exists. -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-templates.html#indices-templates-exists +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-templates.html#indices-templates-exists // for documentation. type IndicesExistsTemplateService struct { client *Client - pretty bool - name string - local *bool + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string + local *bool } // NewIndicesExistsTemplateService creates a new IndicesExistsTemplateService. @@ -30,6 +37,46 @@ func NewIndicesExistsTemplateService(client *Client) *IndicesExistsTemplateServi } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesExistsTemplateService) Pretty(pretty bool) *IndicesExistsTemplateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesExistsTemplateService) Human(human bool) *IndicesExistsTemplateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesExistsTemplateService) ErrorTrace(errorTrace bool) *IndicesExistsTemplateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesExistsTemplateService) FilterPath(filterPath ...string) *IndicesExistsTemplateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesExistsTemplateService) Header(name string, value string) *IndicesExistsTemplateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesExistsTemplateService) Headers(headers http.Header) *IndicesExistsTemplateService { + s.headers = headers + return s +} + // Name is the name of the template. func (s *IndicesExistsTemplateService) Name(name string) *IndicesExistsTemplateService { s.name = name @@ -43,12 +90,6 @@ func (s *IndicesExistsTemplateService) Local(local bool) *IndicesExistsTemplateS return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesExistsTemplateService) Pretty(pretty bool) *IndicesExistsTemplateService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesExistsTemplateService) buildURL() (string, url.Values, error) { // Build URL @@ -61,8 +102,17 @@ func (s *IndicesExistsTemplateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.local != nil { params.Set("local", fmt.Sprintf("%v", *s.local)) @@ -101,6 +151,7 @@ func (s *IndicesExistsTemplateService) Do(ctx context.Context) (bool, error) { Path: path, Params: params, IgnoreErrors: []int{404}, + Headers: s.headers, }) if err != nil { return false, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_flush.go b/vendor/github.com/olivere/elastic/v7/indices_flush.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/indices_flush.go rename to vendor/github.com/olivere/elastic/v7/indices_flush.go index cf14e8e..5d4c4e1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_flush.go +++ b/vendor/github.com/olivere/elastic/v7/indices_flush.go @@ -7,21 +7,28 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/indices-flush.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-flush.html // for details. type IndicesFlushService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string force *bool waitIfOngoing *bool @@ -38,6 +45,46 @@ func NewIndicesFlushService(client *Client) *IndicesFlushService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesFlushService) Pretty(pretty bool) *IndicesFlushService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesFlushService) Human(human bool) *IndicesFlushService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesFlushService) ErrorTrace(errorTrace bool) *IndicesFlushService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesFlushService) FilterPath(filterPath ...string) *IndicesFlushService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesFlushService) Header(name string, value string) *IndicesFlushService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesFlushService) Headers(headers http.Header) *IndicesFlushService { + s.headers = headers + return s +} + // Index is a list of index names; use `_all` or empty string for all indices. func (s *IndicesFlushService) Index(indices ...string) *IndicesFlushService { s.index = append(s.index, indices...) @@ -84,12 +131,6 @@ func (s *IndicesFlushService) ExpandWildcards(expandWildcards string) *IndicesFl return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesFlushService) Pretty(pretty bool) *IndicesFlushService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesFlushService) buildURL() (string, url.Values, error) { // Build URL @@ -109,8 +150,17 @@ func (s *IndicesFlushService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.force != nil { params.Set("force", fmt.Sprintf("%v", *s.force)) @@ -150,9 +200,10 @@ 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, + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -169,5 +220,5 @@ func (s *IndicesFlushService) Do(ctx context.Context) (*IndicesFlushResponse, er // -- Result of a flush request. type IndicesFlushResponse struct { - Shards shardsInfo `json:"_shards"` + Shards *ShardsInfo `json:"_shards"` } diff --git a/vendor/github.com/olivere/elastic/v7/indices_flush_synced.go b/vendor/github.com/olivere/elastic/v7/indices_flush_synced.go new file mode 100644 index 0000000..140ae62 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_flush_synced.go @@ -0,0 +1,281 @@ +// 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesSyncedFlushService performs a normal flush, then adds a generated +// unique marked (sync_id) to all shards. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-synced-flush.html +// for details. +type IndicesSyncedFlushService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index []string + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string +} + +// NewIndicesSyncedFlushService creates a new IndicesSyncedFlushService. +func NewIndicesSyncedFlushService(client *Client) *IndicesSyncedFlushService { + return &IndicesSyncedFlushService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesSyncedFlushService) Pretty(pretty bool) *IndicesSyncedFlushService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesSyncedFlushService) Human(human bool) *IndicesSyncedFlushService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesSyncedFlushService) ErrorTrace(errorTrace bool) *IndicesSyncedFlushService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesSyncedFlushService) FilterPath(filterPath ...string) *IndicesSyncedFlushService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesSyncedFlushService) Header(name string, value string) *IndicesSyncedFlushService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesSyncedFlushService) Headers(headers http.Header) *IndicesSyncedFlushService { + s.headers = headers + return s +} + +// Index is a list of index names; use `_all` or empty string for all indices. +func (s *IndicesSyncedFlushService) Index(indices ...string) *IndicesSyncedFlushService { + s.index = append(s.index, indices...) + return s +} + +// IgnoreUnavailable indicates whether specified concrete indices should be +// ignored when unavailable (missing or closed). +func (s *IndicesSyncedFlushService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesSyncedFlushService { + 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 *IndicesSyncedFlushService) AllowNoIndices(allowNoIndices bool) *IndicesSyncedFlushService { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards specifies whether to expand wildcard expression to +// concrete indices that are open, closed or both.. +func (s *IndicesSyncedFlushService) ExpandWildcards(expandWildcards string) *IndicesSyncedFlushService { + s.expandWildcards = expandWildcards + return s +} + +// buildURL builds the URL for the operation. +func (s *IndicesSyncedFlushService) buildURL() (string, url.Values, error) { + // Build URL + var err error + var path string + + if len(s.index) > 0 { + path, err = uritemplates.Expand("/{index}/_flush/synced", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else { + path = "/_flush/synced" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.ignoreUnavailable != nil { + params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) + } + if s.allowNoIndices != nil { + params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) + } + if s.expandWildcards != "" { + params.Set("expand_wildcards", s.expandWildcards) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *IndicesSyncedFlushService) Validate() error { + return nil +} + +// Do executes the service. +func (s *IndicesSyncedFlushService) Do(ctx context.Context) (*IndicesSyncedFlushResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(IndicesSyncedFlushResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// -- Result of a flush request. + +// IndicesSyncedFlushResponse is the outcome of a synched flush call. +type IndicesSyncedFlushResponse struct { + Shards *ShardsInfo `json:"_shards"` + Index map[string]*IndicesShardsSyncedFlushResult `json:"-"` + + // TODO Add information about the indices here from the root level + // It looks like this: + // { + // "_shards" : { + // "total" : 4, + // "successful" : 4, + // "failed" : 0 + // }, + // "elastic-test" : { + // "total" : 1, + // "successful" : 1, + // "failed" : 0 + // }, + // "elastic-test2" : { + // "total" : 1, + // "successful" : 1, + // "failed" : 0 + // }, + // "elastic-orders" : { + // "total" : 1, + // "successful" : 1, + // "failed" : 0 + // }, + // "elastic-nosource-test" : { + // "total" : 1, + // "successful" : 1, + // "failed" : 0 + // } + // } +} + +// IndicesShardsSyncedFlushResult represents synced flush information about +// a specific index. +type IndicesShardsSyncedFlushResult struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []IndicesShardsSyncedFlushResultFailure `json:"failures,omitempty"` +} + +// IndicesShardsSyncedFlushResultFailure represents a failure of a synced +// flush operation. +type IndicesShardsSyncedFlushResultFailure struct { + Shard int `json:"shard"` + Reason string `json:"reason"` + Routing struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node string `json:"node"` + RelocatingNode *string `json:"relocating_node"` + Shard int `json:"shard"` + Index string `json:"index"` + ExpectedShardSizeInBytes int64 `json:"expected_shard_size_in_bytes,omitempty"` + // recoverySource + // allocationId + // unassignedInfo + } `json:"routing"` +} + +// UnmarshalJSON parses the output from Synced Flush API. +func (resp *IndicesSyncedFlushResponse) UnmarshalJSON(data []byte) error { + m := make(map[string]json.RawMessage) + err := json.Unmarshal(data, &m) + if err != nil { + return err + } + resp.Index = make(map[string]*IndicesShardsSyncedFlushResult) + for k, v := range m { + if k == "_shards" { + if err := json.Unmarshal(v, &resp.Shards); err != nil { + return err + } + } else { + ix := new(IndicesShardsSyncedFlushResult) + if err := json.Unmarshal(v, &ix); err != nil { + return err + } + resp.Index[k] = ix + } + } + return nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_forcemerge.go b/vendor/github.com/olivere/elastic/v7/indices_forcemerge.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/indices_forcemerge.go rename to vendor/github.com/olivere/elastic/v7/indices_forcemerge.go index 0e999cf..8098390 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_forcemerge.go +++ b/vendor/github.com/olivere/elastic/v7/indices_forcemerge.go @@ -7,10 +7,11 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesForcemergeService allows to force merging of one or more indices. @@ -18,11 +19,17 @@ import ( // within each shard. The force merge operation allows to reduce the number // of segments by merging them. // -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-forcemerge.html +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-forcemerge.html // for more information. type IndicesForcemergeService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string allowNoIndices *bool expandWildcards string @@ -30,7 +37,6 @@ type IndicesForcemergeService struct { ignoreUnavailable *bool maxNumSegments interface{} onlyExpungeDeletes *bool - operationThreading interface{} } // NewIndicesForcemergeService creates a new IndicesForcemergeService. @@ -41,6 +47,46 @@ func NewIndicesForcemergeService(client *Client) *IndicesForcemergeService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesForcemergeService) Pretty(pretty bool) *IndicesForcemergeService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesForcemergeService) Human(human bool) *IndicesForcemergeService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesForcemergeService) ErrorTrace(errorTrace bool) *IndicesForcemergeService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesForcemergeService) FilterPath(filterPath ...string) *IndicesForcemergeService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesForcemergeService) Header(name string, value string) *IndicesForcemergeService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesForcemergeService) Headers(headers http.Header) *IndicesForcemergeService { + s.headers = headers + return s +} + // Index is a list of index names; use `_all` or empty string to perform // the operation on all indices. func (s *IndicesForcemergeService) Index(index ...string) *IndicesForcemergeService { @@ -94,17 +140,6 @@ func (s *IndicesForcemergeService) OnlyExpungeDeletes(onlyExpungeDeletes bool) * return s } -func (s *IndicesForcemergeService) OperationThreading(operationThreading interface{}) *IndicesForcemergeService { - s.operationThreading = operationThreading - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesForcemergeService) Pretty(pretty bool) *IndicesForcemergeService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesForcemergeService) buildURL() (string, url.Values, error) { var err error @@ -124,8 +159,17 @@ func (s *IndicesForcemergeService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -145,9 +189,6 @@ func (s *IndicesForcemergeService) buildURL() (string, url.Values, error) { if s.onlyExpungeDeletes != nil { params.Set("only_expunge_deletes", fmt.Sprintf("%v", *s.onlyExpungeDeletes)) } - if s.operationThreading != nil { - params.Set("operation_threading", fmt.Sprintf("%v", s.operationThreading)) - } return path, params, nil } @@ -171,9 +212,10 @@ func (s *IndicesForcemergeService) Do(ctx context.Context) (*IndicesForcemergeRe // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -189,5 +231,5 @@ func (s *IndicesForcemergeService) Do(ctx context.Context) (*IndicesForcemergeRe // IndicesForcemergeResponse is the response of IndicesForcemergeService.Do. type IndicesForcemergeResponse struct { - Shards shardsInfo `json:"_shards"` + Shards *ShardsInfo `json:"_shards"` } diff --git a/vendor/github.com/olivere/elastic/v7/indices_freeze.go b/vendor/github.com/olivere/elastic/v7/indices_freeze.go new file mode 100644 index 0000000..04c2a3e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_freeze.go @@ -0,0 +1,229 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesFreezeService freezes an index. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/freeze-index-api.html +// and https://www.elastic.co/blog/creating-frozen-indices-with-the-elasticsearch-freeze-index-api +// for details. +type IndicesFreezeService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index string + timeout string + masterTimeout string + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string + waitForActiveShards string +} + +// NewIndicesFreezeService creates a new IndicesFreezeService. +func NewIndicesFreezeService(client *Client) *IndicesFreezeService { + return &IndicesFreezeService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesFreezeService) Pretty(pretty bool) *IndicesFreezeService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesFreezeService) Human(human bool) *IndicesFreezeService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesFreezeService) ErrorTrace(errorTrace bool) *IndicesFreezeService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesFreezeService) FilterPath(filterPath ...string) *IndicesFreezeService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesFreezeService) Header(name string, value string) *IndicesFreezeService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesFreezeService) Headers(headers http.Header) *IndicesFreezeService { + s.headers = headers + return s +} + +// Index is the name of the index to freeze. +func (s *IndicesFreezeService) Index(index string) *IndicesFreezeService { + s.index = index + return s +} + +// Timeout allows to specify an explicit timeout. +func (s *IndicesFreezeService) Timeout(timeout string) *IndicesFreezeService { + s.timeout = timeout + return s +} + +// MasterTimeout allows to specify a timeout for connection to master. +func (s *IndicesFreezeService) MasterTimeout(masterTimeout string) *IndicesFreezeService { + s.masterTimeout = masterTimeout + return s +} + +// IgnoreUnavailable indicates whether specified concrete indices should be +// ignored when unavailable (missing or closed). +func (s *IndicesFreezeService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesFreezeService { + 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 *IndicesFreezeService) AllowNoIndices(allowNoIndices bool) *IndicesFreezeService { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards specifies whether to expand wildcard expression to +// concrete indices that are open, closed or both.. +func (s *IndicesFreezeService) ExpandWildcards(expandWildcards string) *IndicesFreezeService { + s.expandWildcards = expandWildcards + return s +} + +// WaitForActiveShards sets the number of active shards to wait for +// before the operation returns. +func (s *IndicesFreezeService) WaitForActiveShards(numShards string) *IndicesFreezeService { + s.waitForActiveShards = numShards + return s +} + +// buildURL builds the URL for the operation. +func (s *IndicesFreezeService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/{index}/_freeze", map[string]string{ + "index": s.index, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if s.expandWildcards != "" { + params.Set("expand_wildcards", s.expandWildcards) + } + if s.ignoreUnavailable != nil { + params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) + } + 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.waitForActiveShards != "" { + params.Set("wait_for_active_shards", s.waitForActiveShards) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *IndicesFreezeService) Validate() error { + var invalid []string + if s.index == "" { + invalid = append(invalid, "Index") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the service. +func (s *IndicesFreezeService) Do(ctx context.Context) (*IndicesFreezeResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(IndicesFreezeResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// IndicesFreezeResponse is the outcome of freezing an index. +type IndicesFreezeResponse struct { + Shards *ShardsInfo `json:"_shards"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get.go b/vendor/github.com/olivere/elastic/v7/indices_get.go similarity index 71% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get.go rename to vendor/github.com/olivere/elastic/v7/indices_get.go index 204703d..6416c04 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get.go @@ -7,19 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesGetService retrieves information about one or more indices. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-get-index.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-get-index.html // for more details. type IndicesGetService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string feature []string local *bool @@ -27,7 +34,6 @@ type IndicesGetService struct { allowNoIndices *bool expandWildcards string flatSettings *bool - human *bool } // NewIndicesGetService creates a new IndicesGetService. @@ -39,6 +45,46 @@ func NewIndicesGetService(client *Client) *IndicesGetService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesGetService) Pretty(pretty bool) *IndicesGetService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesGetService) Human(human bool) *IndicesGetService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesGetService) ErrorTrace(errorTrace bool) *IndicesGetService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesGetService) FilterPath(filterPath ...string) *IndicesGetService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesGetService) Header(name string, value string) *IndicesGetService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesGetService) Headers(headers http.Header) *IndicesGetService { + s.headers = headers + return s +} + // Index is a list of index names. func (s *IndicesGetService) Index(indices ...string) *IndicesGetService { s.index = append(s.index, indices...) @@ -78,28 +124,6 @@ func (s *IndicesGetService) ExpandWildcards(expandWildcards string) *IndicesGetS return s } -/* Disabled because serialization would fail in that case. */ -/* -// FlatSettings make the service return settings in flat format (default: false). -func (s *IndicesGetService) FlatSettings(flatSettings bool) *IndicesGetService { - s.flatSettings = &flatSettings - return s -} -*/ - -// Human indicates whether to return version and creation date values -// in human-readable format (default: false). -func (s *IndicesGetService) Human(human bool) *IndicesGetService { - s.human = &human - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesGetService) Pretty(pretty bool) *IndicesGetService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesGetService) buildURL() (string, url.Values, error) { var err error @@ -130,8 +154,17 @@ func (s *IndicesGetService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) @@ -139,9 +172,6 @@ func (s *IndicesGetService) buildURL() (string, url.Values, error) { if s.flatSettings != nil { params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings)) } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) - } if s.local != nil { params.Set("local", fmt.Sprintf("%v", *s.local)) } @@ -181,9 +211,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get_aliases.go b/vendor/github.com/olivere/elastic/v7/indices_get_aliases.go similarity index 55% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get_aliases.go rename to vendor/github.com/olivere/elastic/v7/indices_get_aliases.go index 6d895da..596dc60 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get_aliases.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get_aliases.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // AliasesService returns the aliases associated with one or more indices, or the // indices associated with one or more aliases, or a combination of those filters. -// See http://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-aliases.html. +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-aliases.html. type AliasesService struct { client *Client - index []string - alias []string - pretty bool + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index []string + alias []string } // NewAliasesService instantiates a new AliasesService. @@ -31,9 +38,43 @@ func NewAliasesService(client *Client) *AliasesService { return builder } -// Pretty asks Elasticsearch to indent the returned JSON. +// Pretty tells Elasticsearch whether to return a formatted JSON response. func (s *AliasesService) Pretty(pretty bool) *AliasesService { - s.pretty = pretty + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *AliasesService) Human(human bool) *AliasesService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *AliasesService) ErrorTrace(errorTrace bool) *AliasesService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *AliasesService) FilterPath(filterPath ...string) *AliasesService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *AliasesService) Header(name string, value string) *AliasesService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *AliasesService) Headers(headers http.Header) *AliasesService { + s.headers = headers return s } @@ -71,8 +112,17 @@ func (s *AliasesService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", fmt.Sprintf("%v", s.pretty)) + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } return path, params, nil } @@ -85,9 +135,10 @@ func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error) { // Get response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -104,7 +155,11 @@ func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error) { // ... // }, // } - indexMap := make(map[string]interface{}) + indexMap := make(map[string]struct { + Aliases map[string]struct { + IsWriteIndex bool `json:"is_write_index"` + } `json:"aliases"` + }) if err := s.client.decoder.Decode(res.Body, &indexMap); err != nil { return nil, err } @@ -114,21 +169,19 @@ func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error) { Indices: make(map[string]indexResult), } for indexName, indexData := range indexMap { + if indexData.Aliases == nil { + continue + } + indexOut, found := ret.Indices[indexName] if !found { indexOut = indexResult{Aliases: make([]aliasResult, 0)} } // { "aliases" : { ... } } - indexDataMap, ok := indexData.(map[string]interface{}) - if ok { - aliasesData, ok := indexDataMap["aliases"].(map[string]interface{}) - if ok { - for aliasName, _ := range aliasesData { - aliasRes := aliasResult{AliasName: aliasName} - indexOut.Aliases = append(indexOut.Aliases, aliasRes) - } - } + for aliasName, aliasData := range indexData.Aliases { + aliasRes := aliasResult{AliasName: aliasName, IsWriteIndex: aliasData.IsWriteIndex} + indexOut.Aliases = append(indexOut.Aliases, aliasRes) } ret.Indices[indexName] = indexOut @@ -139,6 +192,7 @@ func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error) { // -- Result of an alias request. +// AliasesResult is the outcome of calling AliasesService.Do. type AliasesResult struct { Indices map[string]indexResult } @@ -148,9 +202,11 @@ type indexResult struct { } type aliasResult struct { - AliasName string + AliasName string + IsWriteIndex bool } +// IndicesByAlias returns all indices given a specific alias name. func (ar AliasesResult) IndicesByAlias(aliasName string) []string { var indices []string for indexName, indexInfo := range ar.Indices { @@ -163,6 +219,7 @@ func (ar AliasesResult) IndicesByAlias(aliasName string) []string { return indices } +// HasAlias returns true if the index has a specific alias. func (ir indexResult) HasAlias(aliasName string) bool { for _, alias := range ir.Aliases { if alias.AliasName == aliasName { diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get_field_mapping.go b/vendor/github.com/olivere/elastic/v7/indices_get_field_mapping.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get_field_mapping.go rename to vendor/github.com/olivere/elastic/v7/indices_get_field_mapping.go index 20f0196..5875af5 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get_field_mapping.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get_field_mapping.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/indices-get-field-mapping.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-get-field-mapping.html // for details. type IndicesGetFieldMappingService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string field []string @@ -43,6 +50,46 @@ func NewIndicesGetFieldMappingService(client *Client) *IndicesGetFieldMappingSer } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesGetFieldMappingService) Pretty(pretty bool) *IndicesGetFieldMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesGetFieldMappingService) Human(human bool) *IndicesGetFieldMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesGetFieldMappingService) ErrorTrace(errorTrace bool) *IndicesGetFieldMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesGetFieldMappingService) FilterPath(filterPath ...string) *IndicesGetFieldMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesGetFieldMappingService) Header(name string, value string) *IndicesGetFieldMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesGetFieldMappingService) Headers(headers http.Header) *IndicesGetFieldMappingService { + s.headers = headers + return s +} + // Index is a list of index names. func (s *IndicesGetFieldMappingService) Index(indices ...string) *IndicesGetFieldMappingService { s.index = append(s.index, indices...) @@ -90,12 +137,6 @@ func (s *IndicesGetFieldMappingService) IgnoreUnavailable(ignoreUnavailable bool return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesGetFieldMappingService) Pretty(pretty bool) *IndicesGetFieldMappingService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesGetFieldMappingService) buildURL() (string, url.Values, error) { var index, typ, field []string @@ -130,8 +171,17 @@ func (s *IndicesGetFieldMappingService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) @@ -171,9 +221,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get_mapping.go b/vendor/github.com/olivere/elastic/v7/indices_get_mapping.go similarity index 68% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get_mapping.go rename to vendor/github.com/olivere/elastic/v7/indices_get_mapping.go index 2533ede..3520163 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get_mapping.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get_mapping.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesGetMappingService retrieves the mapping definitions for an index or // index/type. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-get-mapping.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-get-mapping.html // for details. type IndicesGetMappingService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string local *bool @@ -44,6 +51,46 @@ func NewIndicesGetMappingService(client *Client) *IndicesGetMappingService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesGetMappingService) Pretty(pretty bool) *IndicesGetMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesGetMappingService) Human(human bool) *IndicesGetMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesGetMappingService) ErrorTrace(errorTrace bool) *IndicesGetMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesGetMappingService) FilterPath(filterPath ...string) *IndicesGetMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesGetMappingService) Header(name string, value string) *IndicesGetMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesGetMappingService) Headers(headers http.Header) *IndicesGetMappingService { + s.headers = headers + return s +} + // Index is a list of index names. func (s *IndicesGetMappingService) Index(indices ...string) *IndicesGetMappingService { s.index = append(s.index, indices...) @@ -85,12 +132,6 @@ func (s *IndicesGetMappingService) IgnoreUnavailable(ignoreUnavailable bool) *In return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesGetMappingService) Pretty(pretty bool) *IndicesGetMappingService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesGetMappingService) buildURL() (string, url.Values, error) { var index, typ []string @@ -118,8 +159,17 @@ func (s *IndicesGetMappingService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) @@ -157,9 +207,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get_settings.go b/vendor/github.com/olivere/elastic/v7/indices_get_settings.go similarity index 70% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get_settings.go rename to vendor/github.com/olivere/elastic/v7/indices_get_settings.go index d63afce..2f7e4d4 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get_settings.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get_settings.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesGetSettingsService allows to retrieve settings of one // or more indices. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-get-settings.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-get-settings.html // for more details. type IndicesGetSettingsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string name []string ignoreUnavailable *bool @@ -39,6 +46,46 @@ func NewIndicesGetSettingsService(client *Client) *IndicesGetSettingsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesGetSettingsService) Pretty(pretty bool) *IndicesGetSettingsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesGetSettingsService) Human(human bool) *IndicesGetSettingsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesGetSettingsService) ErrorTrace(errorTrace bool) *IndicesGetSettingsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesGetSettingsService) FilterPath(filterPath ...string) *IndicesGetSettingsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesGetSettingsService) Header(name string, value string) *IndicesGetSettingsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesGetSettingsService) Headers(headers http.Header) *IndicesGetSettingsService { + s.headers = headers + return s +} + // Index is a list of index names; use `_all` or empty string to perform // the operation on all indices. func (s *IndicesGetSettingsService) Index(indices ...string) *IndicesGetSettingsService { @@ -88,12 +135,6 @@ func (s *IndicesGetSettingsService) Local(local bool) *IndicesGetSettingsService return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesGetSettingsService) Pretty(pretty bool) *IndicesGetSettingsService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesGetSettingsService) buildURL() (string, url.Values, error) { var err error @@ -124,8 +165,17 @@ func (s *IndicesGetSettingsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) @@ -165,9 +215,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_get_template.go b/vendor/github.com/olivere/elastic/v7/indices_get_template.go similarity index 54% rename from vendor/gopkg.in/olivere/elastic.v6/indices_get_template.go rename to vendor/github.com/olivere/elastic/v7/indices_get_template.go index faaa6ee..aeafe91 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_get_template.go +++ b/vendor/github.com/olivere/elastic/v7/indices_get_template.go @@ -7,17 +7,24 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesGetTemplateService returns an index template. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-templates.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-templates.html. type IndicesGetTemplateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + name []string flatSettings *bool local *bool @@ -31,6 +38,46 @@ func NewIndicesGetTemplateService(client *Client) *IndicesGetTemplateService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesGetTemplateService) Pretty(pretty bool) *IndicesGetTemplateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesGetTemplateService) Human(human bool) *IndicesGetTemplateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesGetTemplateService) ErrorTrace(errorTrace bool) *IndicesGetTemplateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesGetTemplateService) FilterPath(filterPath ...string) *IndicesGetTemplateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesGetTemplateService) Header(name string, value string) *IndicesGetTemplateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesGetTemplateService) Headers(headers http.Header) *IndicesGetTemplateService { + s.headers = headers + return s +} + // Name is the name of the index template. func (s *IndicesGetTemplateService) Name(name ...string) *IndicesGetTemplateService { s.name = append(s.name, name...) @@ -50,12 +97,6 @@ func (s *IndicesGetTemplateService) Local(local bool) *IndicesGetTemplateService return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesGetTemplateService) Pretty(pretty bool) *IndicesGetTemplateService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesGetTemplateService) buildURL() (string, url.Values, error) { // Build URL @@ -74,8 +115,17 @@ func (s *IndicesGetTemplateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.flatSettings != nil { params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings)) @@ -106,9 +156,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -124,10 +175,10 @@ func (s *IndicesGetTemplateService) Do(ctx context.Context) (map[string]*Indices // IndicesGetTemplateResponse is the response of IndicesGetTemplateService.Do. type IndicesGetTemplateResponse struct { - Order int `json:"order,omitempty"` - Version int `json:"version,omitempty"` - Template string `json:"template,omitempty"` - Settings map[string]interface{} `json:"settings,omitempty"` - Mappings map[string]interface{} `json:"mappings,omitempty"` - Aliases map[string]interface{} `json:"aliases,omitempty"` + Order int `json:"order,omitempty"` + Version int `json:"version,omitempty"` + IndexPatterns []string `json:"index_patterns,omitempty"` + Settings map[string]interface{} `json:"settings,omitempty"` + Mappings map[string]interface{} `json:"mappings,omitempty"` + Aliases map[string]interface{} `json:"aliases,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_open.go b/vendor/github.com/olivere/elastic/v7/indices_open.go similarity index 59% rename from vendor/gopkg.in/olivere/elastic.v6/indices_open.go rename to vendor/github.com/olivere/elastic/v7/indices_open.go index 4cd4b06..81ad90f 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_open.go +++ b/vendor/github.com/olivere/elastic/v7/indices_open.go @@ -7,24 +7,33 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesOpenService opens an index. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-open-close.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-open-close.html // for details. type IndicesOpenService struct { - client *Client - pretty bool - index string - timeout string - masterTimeout string - ignoreUnavailable *bool - allowNoIndices *bool - expandWildcards string + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index string + timeout string + masterTimeout string + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string + waitForActiveShards string } // NewIndicesOpenService creates and initializes a new IndicesOpenService. @@ -32,6 +41,46 @@ func NewIndicesOpenService(client *Client) *IndicesOpenService { return &IndicesOpenService{client: client} } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesOpenService) Pretty(pretty bool) *IndicesOpenService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesOpenService) Human(human bool) *IndicesOpenService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesOpenService) ErrorTrace(errorTrace bool) *IndicesOpenService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesOpenService) FilterPath(filterPath ...string) *IndicesOpenService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesOpenService) Header(name string, value string) *IndicesOpenService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesOpenService) Headers(headers http.Header) *IndicesOpenService { + s.headers = headers + return s +} + // Index is the name of the index to open. func (s *IndicesOpenService) Index(index string) *IndicesOpenService { s.index = index @@ -72,9 +121,11 @@ func (s *IndicesOpenService) ExpandWildcards(expandWildcards string) *IndicesOpe return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesOpenService) Pretty(pretty bool) *IndicesOpenService { - s.pretty = pretty +// WaitForActiveShards specifies the number of shards that must be allocated +// before the Open operation returns. Valid values are "all" or an integer +// between 0 and number_of_replicas+1 (default: 0) +func (s *IndicesOpenService) WaitForActiveShards(waitForActiveShards string) *IndicesOpenService { + s.waitForActiveShards = waitForActiveShards return s } @@ -90,8 +141,17 @@ func (s *IndicesOpenService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.timeout != "" { params.Set("timeout", s.timeout) @@ -108,6 +168,9 @@ func (s *IndicesOpenService) buildURL() (string, url.Values, error) { if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) } + if s.waitForActiveShards != "" { + params.Set("wait_for_active_shards", s.waitForActiveShards) + } return path, params, nil } @@ -139,9 +202,10 @@ 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, + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_put_alias.go b/vendor/github.com/olivere/elastic/v7/indices_put_alias.go similarity index 77% rename from vendor/gopkg.in/olivere/elastic.v6/indices_put_alias.go rename to vendor/github.com/olivere/elastic/v7/indices_put_alias.go index 4ad8452..b723eb9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_put_alias.go +++ b/vendor/github.com/olivere/elastic/v7/indices_put_alias.go @@ -7,6 +7,7 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" ) @@ -26,6 +27,7 @@ type AliasAddAction struct { routing string searchRouting string indexRouting string + isWriteIndex *bool } // NewAliasAddAction returns an action to add an alias. @@ -76,6 +78,12 @@ func (a *AliasAddAction) SearchRouting(routing ...string) *AliasAddAction { return a } +// IsWriteIndex associates an is_write_index flag to the alias. +func (a *AliasAddAction) IsWriteIndex(flag bool) *AliasAddAction { + a.isWriteIndex = &flag + return a +} + // Validate checks if the operation is valid. func (a *AliasAddAction) Validate() error { var invalid []string @@ -88,6 +96,9 @@ func (a *AliasAddAction) Validate() error { if len(invalid) > 0 { return fmt.Errorf("missing required fields: %v", invalid) } + if a.isWriteIndex != nil && len(a.index) > 1 { + return fmt.Errorf("more than 1 target index specified in operation with 'is_write_index' flag present") + } return nil } @@ -123,6 +134,9 @@ func (a *AliasAddAction) Source() (interface{}, error) { if len(a.searchRouting) > 0 { act["search_routing"] = a.searchRouting } + if a.isWriteIndex != nil { + act["is_write_index"] = *a.isWriteIndex + } return src, nil } @@ -225,12 +239,18 @@ func (a *AliasRemoveIndexAction) Source() (interface{}, error) { // -- Service -- // AliasService enables users to add or remove an alias. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-aliases.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-aliases.html // for details. type AliasService struct { - client *Client + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + actions []AliasAction - pretty bool } // NewAliasService implements a service to manage aliases. @@ -241,9 +261,43 @@ func NewAliasService(client *Client) *AliasService { return builder } -// Pretty asks Elasticsearch to indent the HTTP response. +// Pretty tells Elasticsearch whether to return a formatted JSON response. func (s *AliasService) Pretty(pretty bool) *AliasService { - s.pretty = pretty + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *AliasService) Human(human bool) *AliasService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *AliasService) ErrorTrace(errorTrace bool) *AliasService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *AliasService) FilterPath(filterPath ...string) *AliasService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *AliasService) Header(name string, value string) *AliasService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *AliasService) Headers(headers http.Header) *AliasService { + s.headers = headers return s } @@ -281,8 +335,17 @@ func (s *AliasService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", fmt.Sprintf("%v", s.pretty)) + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } return path, params, nil } @@ -308,10 +371,11 @@ func (s *AliasService) Do(ctx context.Context) (*AliasResult, error) { // Get response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_put_mapping.go b/vendor/github.com/olivere/elastic/v7/indices_put_mapping.go similarity index 71% rename from vendor/gopkg.in/olivere/elastic.v6/indices_put_mapping.go rename to vendor/github.com/olivere/elastic/v7/indices_put_mapping.go index 04254d3..eae320a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_put_mapping.go +++ b/vendor/github.com/olivere/elastic/v7/indices_put_mapping.go @@ -7,21 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesPutMappingService allows to register specific mapping definition // for a specific type. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-put-mapping.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-put-mapping.html // for details. type IndicesPutMappingService struct { - client *Client - pretty bool - typ string + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string masterTimeout string ignoreUnavailable *bool @@ -47,6 +53,46 @@ func NewIndicesPutMappingService(client *Client) *IndicesPutMappingService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesPutMappingService) Pretty(pretty bool) *IndicesPutMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesPutMappingService) Human(human bool) *IndicesPutMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesPutMappingService) ErrorTrace(errorTrace bool) *IndicesPutMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesPutMappingService) FilterPath(filterPath ...string) *IndicesPutMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesPutMappingService) Header(name string, value string) *IndicesPutMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesPutMappingService) Headers(headers http.Header) *IndicesPutMappingService { + s.headers = headers + return s +} + // Index is a list of index names the mapping should be added to // (supports wildcards); use `_all` or omit to add the mapping on all indices. func (s *IndicesPutMappingService) Index(indices ...string) *IndicesPutMappingService { @@ -54,12 +100,6 @@ func (s *IndicesPutMappingService) Index(indices ...string) *IndicesPutMappingSe return s } -// Type is the name of the document type. -func (s *IndicesPutMappingService) Type(typ string) *IndicesPutMappingService { - s.typ = typ - return s -} - // Timeout is an explicit operation timeout. func (s *IndicesPutMappingService) Timeout(timeout string) *IndicesPutMappingService { s.timeout = timeout @@ -101,12 +141,6 @@ func (s *IndicesPutMappingService) UpdateAllTypes(updateAllTypes bool) *IndicesP return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesPutMappingService) Pretty(pretty bool) *IndicesPutMappingService { - s.pretty = pretty - return s -} - // BodyJson contains the mapping definition. func (s *IndicesPutMappingService) BodyJson(mapping map[string]interface{}) *IndicesPutMappingService { s.bodyJson = mapping @@ -121,28 +155,26 @@ func (s *IndicesPutMappingService) BodyString(mapping string) *IndicesPutMapping // buildURL builds the URL for the operation. func (s *IndicesPutMappingService) buildURL() (string, url.Values, error) { - var err error - var path string - - // Build URL: Typ MUST be specified and is verified in Validate. - if len(s.index) > 0 { - path, err = uritemplates.Expand("/{index}/_mapping/{type}", map[string]string{ - "index": strings.Join(s.index, ","), - "type": s.typ, - }) - } else { - path, err = uritemplates.Expand("/_mapping/{type}", map[string]string{ - "type": s.typ, - }) - } + path, err := uritemplates.Expand("/{index}/_mapping", 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 v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) @@ -168,8 +200,8 @@ func (s *IndicesPutMappingService) buildURL() (string, url.Values, error) { // Validate checks if the operation is valid. func (s *IndicesPutMappingService) Validate() error { var invalid []string - if s.typ == "" { - invalid = append(invalid, "Type") + if len(s.index) == 0 { + invalid = append(invalid, "Index") } if s.bodyString == "" && s.bodyJson == nil { invalid = append(invalid, "BodyJson") @@ -203,10 +235,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_put_settings.go b/vendor/github.com/olivere/elastic/v7/indices_put_settings.go similarity index 71% rename from vendor/gopkg.in/olivere/elastic.v6/indices_put_settings.go rename to vendor/github.com/olivere/elastic/v7/indices_put_settings.go index 92308c4..c8c0811 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_put_settings.go +++ b/vendor/github.com/olivere/elastic/v7/indices_put_settings.go @@ -7,20 +7,27 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesPutSettingsService changes specific index level settings in // real time. // // See the documentation at -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-update-settings.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-update-settings.html. type IndicesPutSettingsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string allowNoIndices *bool expandWildcards string @@ -39,6 +46,46 @@ func NewIndicesPutSettingsService(client *Client) *IndicesPutSettingsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesPutSettingsService) Pretty(pretty bool) *IndicesPutSettingsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesPutSettingsService) Human(human bool) *IndicesPutSettingsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesPutSettingsService) ErrorTrace(errorTrace bool) *IndicesPutSettingsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesPutSettingsService) FilterPath(filterPath ...string) *IndicesPutSettingsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesPutSettingsService) Header(name string, value string) *IndicesPutSettingsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesPutSettingsService) Headers(headers http.Header) *IndicesPutSettingsService { + s.headers = headers + return s +} + // Index is a list of index names the mapping should be added to // (supports wildcards); use `_all` or omit to add the mapping on all indices. func (s *IndicesPutSettingsService) Index(indices ...string) *IndicesPutSettingsService { @@ -80,12 +127,6 @@ func (s *IndicesPutSettingsService) MasterTimeout(masterTimeout string) *Indices return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesPutSettingsService) Pretty(pretty bool) *IndicesPutSettingsService { - s.pretty = pretty - return s -} - // BodyJson is documented as: The index settings to be updated. func (s *IndicesPutSettingsService) BodyJson(body interface{}) *IndicesPutSettingsService { s.bodyJson = body @@ -117,8 +158,17 @@ func (s *IndicesPutSettingsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -166,10 +216,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_put_template.go b/vendor/github.com/olivere/elastic/v7/indices_put_template.go similarity index 71% rename from vendor/gopkg.in/olivere/elastic.v6/indices_put_template.go rename to vendor/github.com/olivere/elastic/v7/indices_put_template.go index a8750ea..4ced8e8 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_put_template.go +++ b/vendor/github.com/olivere/elastic/v7/indices_put_template.go @@ -7,16 +7,24 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesPutTemplateService creates or updates index mappings. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-templates.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-templates.html. type IndicesPutTemplateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + name string cause string order interface{} @@ -36,6 +44,46 @@ func NewIndicesPutTemplateService(client *Client) *IndicesPutTemplateService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesPutTemplateService) Pretty(pretty bool) *IndicesPutTemplateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesPutTemplateService) Human(human bool) *IndicesPutTemplateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesPutTemplateService) ErrorTrace(errorTrace bool) *IndicesPutTemplateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesPutTemplateService) FilterPath(filterPath ...string) *IndicesPutTemplateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesPutTemplateService) Header(name string, value string) *IndicesPutTemplateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesPutTemplateService) Headers(headers http.Header) *IndicesPutTemplateService { + s.headers = headers + return s +} + // Name is the name of the index template. func (s *IndicesPutTemplateService) Name(name string) *IndicesPutTemplateService { s.name = name @@ -87,12 +135,6 @@ func (s *IndicesPutTemplateService) Create(create bool) *IndicesPutTemplateServi return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesPutTemplateService) Pretty(pretty bool) *IndicesPutTemplateService { - s.pretty = pretty - return s -} - // BodyJson is documented as: The template definition. func (s *IndicesPutTemplateService) BodyJson(body interface{}) *IndicesPutTemplateService { s.bodyJson = body @@ -117,8 +159,17 @@ func (s *IndicesPutTemplateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.order != nil { params.Set("order", fmt.Sprintf("%v", s.order)) @@ -182,10 +233,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/indices_refresh.go b/vendor/github.com/olivere/elastic/v7/indices_refresh.go new file mode 100644 index 0000000..4dfdbe4 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_refresh.go @@ -0,0 +1,149 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// RefreshService explicitly refreshes one or more indices. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-refresh.html. +type RefreshService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index []string +} + +// NewRefreshService creates a new instance of RefreshService. +func NewRefreshService(client *Client) *RefreshService { + builder := &RefreshService{ + client: client, + } + return builder +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *RefreshService) Pretty(pretty bool) *RefreshService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *RefreshService) Human(human bool) *RefreshService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *RefreshService) ErrorTrace(errorTrace bool) *RefreshService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *RefreshService) FilterPath(filterPath ...string) *RefreshService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *RefreshService) Header(name string, value string) *RefreshService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *RefreshService) Headers(headers http.Header) *RefreshService { + s.headers = headers + return s +} + +// Index specifies the indices to refresh. +func (s *RefreshService) Index(index ...string) *RefreshService { + s.index = append(s.index, index...) + return s +} + +// buildURL builds the URL for the operation. +func (s *RefreshService) buildURL() (string, url.Values, error) { + var err error + var path string + + if len(s.index) > 0 { + path, err = uritemplates.Expand("/{index}/_refresh", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else { + path = "/_refresh" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Do executes the request. +func (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) { + path, params, err := s.buildURL() + if err != nil { + return nil, err + } + + // Get response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return result + ret := new(RefreshResult) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// -- Result of a refresh request. + +// RefreshResult is the outcome of RefreshService.Do. +type RefreshResult struct { + Shards *ShardsInfo `json:"_shards,omitempty"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_rollover.go b/vendor/github.com/olivere/elastic/v7/indices_rollover.go similarity index 78% rename from vendor/gopkg.in/olivere/elastic.v6/indices_rollover.go rename to vendor/github.com/olivere/elastic/v7/indices_rollover.go index 5f5fed3..ce72ef1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_rollover.go +++ b/vendor/github.com/olivere/elastic/v7/indices_rollover.go @@ -8,19 +8,27 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/indices-rollover-index.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-rollover-index.html. type IndicesRolloverService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + dryRun bool newIndex string alias string @@ -44,6 +52,46 @@ func NewIndicesRolloverService(client *Client) *IndicesRolloverService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesRolloverService) Pretty(pretty bool) *IndicesRolloverService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesRolloverService) Human(human bool) *IndicesRolloverService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesRolloverService) ErrorTrace(errorTrace bool) *IndicesRolloverService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesRolloverService) FilterPath(filterPath ...string) *IndicesRolloverService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesRolloverService) Header(name string, value string) *IndicesRolloverService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesRolloverService) Headers(headers http.Header) *IndicesRolloverService { + s.headers = headers + return s +} + // Alias is the name of the alias to rollover. func (s *IndicesRolloverService) Alias(alias string) *IndicesRolloverService { s.alias = alias @@ -75,12 +123,6 @@ func (s *IndicesRolloverService) WaitForActiveShards(waitForActiveShards string) return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesRolloverService) Pretty(pretty bool) *IndicesRolloverService { - s.pretty = pretty - return s -} - // DryRun, when set, specifies that only conditions are checked without // performing the actual rollover. func (s *IndicesRolloverService) DryRun(dryRun bool) *IndicesRolloverService { @@ -188,8 +230,17 @@ func (s *IndicesRolloverService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.dryRun { params.Set("dry_run", "true") @@ -243,10 +294,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_segments.go b/vendor/github.com/olivere/elastic/v7/indices_segments.go similarity index 79% rename from vendor/gopkg.in/olivere/elastic.v6/indices_segments.go rename to vendor/github.com/olivere/elastic/v7/indices_segments.go index 92ad833..01c5c8d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_segments.go +++ b/vendor/github.com/olivere/elastic/v7/indices_segments.go @@ -8,10 +8,11 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IndicesSegmentsService provides low level segments information that a @@ -20,15 +21,20 @@ import ( // optimization information, data "wasted" on deletes, and so on. // // Find further documentation at -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-segments.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-segments.html. type IndicesSegmentsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string allowNoIndices *bool expandWildcards string ignoreUnavailable *bool - human *bool operationThreading interface{} verbose *bool } @@ -40,6 +46,46 @@ func NewIndicesSegmentsService(client *Client) *IndicesSegmentsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesSegmentsService) Pretty(pretty bool) *IndicesSegmentsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesSegmentsService) Human(human bool) *IndicesSegmentsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesSegmentsService) ErrorTrace(errorTrace bool) *IndicesSegmentsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesSegmentsService) FilterPath(filterPath ...string) *IndicesSegmentsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesSegmentsService) Header(name string, value string) *IndicesSegmentsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesSegmentsService) Headers(headers http.Header) *IndicesSegmentsService { + s.headers = headers + return s +} + // Index is a comma-separated list of index names; use `_all` or empty string // to perform the operation on all indices. func (s *IndicesSegmentsService) Index(indices ...string) *IndicesSegmentsService { @@ -69,12 +115,6 @@ func (s *IndicesSegmentsService) IgnoreUnavailable(ignoreUnavailable bool) *Indi return s } -// Human, when set to true, returns time and byte-values in human-readable format. -func (s *IndicesSegmentsService) Human(human bool) *IndicesSegmentsService { - s.human = &human - return s -} - // OperationThreading is undocumented in Elasticsearch as of now. func (s *IndicesSegmentsService) OperationThreading(operationThreading interface{}) *IndicesSegmentsService { s.operationThreading = operationThreading @@ -87,12 +127,6 @@ func (s *IndicesSegmentsService) Verbose(verbose bool) *IndicesSegmentsService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesSegmentsService) Pretty(pretty bool) *IndicesSegmentsService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IndicesSegmentsService) buildURL() (string, url.Values, error) { var err error @@ -111,8 +145,17 @@ func (s *IndicesSegmentsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -123,9 +166,6 @@ func (s *IndicesSegmentsService) buildURL() (string, url.Values, error) { if s.ignoreUnavailable != nil { params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) - } if s.operationThreading != nil { params.Set("operation_threading", fmt.Sprintf("%v", s.operationThreading)) } @@ -155,9 +195,10 @@ func (s *IndicesSegmentsService) Do(ctx context.Context) (*IndicesSegmentsRespon // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -174,7 +215,7 @@ func (s *IndicesSegmentsService) Do(ctx context.Context) (*IndicesSegmentsRespon // IndicesSegmentsResponse is the response of IndicesSegmentsService.Do. type IndicesSegmentsResponse struct { // Shards provides information returned from shards. - Shards shardsInfo `json:"_shards"` + Shards *ShardsInfo `json:"_shards"` // Indices provides a map into the stats of an index. // The key of the map is the index name. diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_shrink.go b/vendor/github.com/olivere/elastic/v7/indices_shrink.go similarity index 68% rename from vendor/gopkg.in/olivere/elastic.v6/indices_shrink.go rename to vendor/github.com/olivere/elastic/v7/indices_shrink.go index 275614b..76cec61 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_shrink.go +++ b/vendor/github.com/olivere/elastic/v7/indices_shrink.go @@ -8,19 +8,27 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/indices-shrink-index.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-shrink-index.html. type IndicesShrinkService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + source string target string masterTimeout string @@ -37,6 +45,46 @@ func NewIndicesShrinkService(client *Client) *IndicesShrinkService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesShrinkService) Pretty(pretty bool) *IndicesShrinkService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesShrinkService) Human(human bool) *IndicesShrinkService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesShrinkService) ErrorTrace(errorTrace bool) *IndicesShrinkService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesShrinkService) FilterPath(filterPath ...string) *IndicesShrinkService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesShrinkService) Header(name string, value string) *IndicesShrinkService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesShrinkService) Headers(headers http.Header) *IndicesShrinkService { + s.headers = headers + return s +} + // Source is the name of the source index to shrink. func (s *IndicesShrinkService) Source(source string) *IndicesShrinkService { s.source = source @@ -68,12 +116,6 @@ func (s *IndicesShrinkService) WaitForActiveShards(waitForActiveShards string) * return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesShrinkService) Pretty(pretty bool) *IndicesShrinkService { - s.pretty = pretty - return s -} - // BodyJson is the configuration for the target index (`settings` and `aliases`) // defined as a JSON-serializable instance to be sent as the request body. func (s *IndicesShrinkService) BodyJson(body interface{}) *IndicesShrinkService { @@ -101,8 +143,17 @@ func (s *IndicesShrinkService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -154,10 +205,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/indices_stats.go b/vendor/github.com/olivere/elastic/v7/indices_stats.go new file mode 100644 index 0000000..397d638 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_stats.go @@ -0,0 +1,530 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesStatsService provides stats on various metrics of one or more +// indices. See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-stats.html. +type IndicesStatsService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + metric []string + index []string + level string + types []string + completionFields []string + fielddataFields []string + fields []string + groups []string +} + +// NewIndicesStatsService creates a new IndicesStatsService. +func NewIndicesStatsService(client *Client) *IndicesStatsService { + return &IndicesStatsService{ + client: client, + index: make([]string, 0), + metric: make([]string, 0), + completionFields: make([]string, 0), + fielddataFields: make([]string, 0), + fields: make([]string, 0), + groups: make([]string, 0), + types: make([]string, 0), + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesStatsService) Pretty(pretty bool) *IndicesStatsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesStatsService) Human(human bool) *IndicesStatsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesStatsService) ErrorTrace(errorTrace bool) *IndicesStatsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesStatsService) FilterPath(filterPath ...string) *IndicesStatsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesStatsService) Header(name string, value string) *IndicesStatsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesStatsService) Headers(headers http.Header) *IndicesStatsService { + s.headers = headers + return s +} + +// Metric limits the information returned the specific metrics. Options are: +// docs, store, indexing, get, search, completion, fielddata, flush, merge, +// query_cache, refresh, suggest, and warmer. +func (s *IndicesStatsService) Metric(metric ...string) *IndicesStatsService { + s.metric = append(s.metric, metric...) + return s +} + +// Index is the list of index names; use `_all` or empty string to perform +// the operation on all indices. +func (s *IndicesStatsService) Index(indices ...string) *IndicesStatsService { + s.index = append(s.index, indices...) + return s +} + +// Type is a list of document types for the `indexing` index metric. +func (s *IndicesStatsService) Type(types ...string) *IndicesStatsService { + s.types = append(s.types, types...) + return s +} + +// Level returns stats aggregated at cluster, index or shard level. +func (s *IndicesStatsService) Level(level string) *IndicesStatsService { + s.level = level + return s +} + +// CompletionFields is a list of fields for `fielddata` and `suggest` +// index metric (supports wildcards). +func (s *IndicesStatsService) CompletionFields(completionFields ...string) *IndicesStatsService { + s.completionFields = append(s.completionFields, completionFields...) + return s +} + +// FielddataFields is a list of fields for `fielddata` index metric (supports wildcards). +func (s *IndicesStatsService) FielddataFields(fielddataFields ...string) *IndicesStatsService { + s.fielddataFields = append(s.fielddataFields, fielddataFields...) + return s +} + +// Fields is a list of fields for `fielddata` and `completion` index metric +// (supports wildcards). +func (s *IndicesStatsService) Fields(fields ...string) *IndicesStatsService { + s.fields = append(s.fields, fields...) + return s +} + +// Groups is a list of search groups for `search` index metric. +func (s *IndicesStatsService) Groups(groups ...string) *IndicesStatsService { + s.groups = append(s.groups, groups...) + return s +} + +// buildURL builds the URL for the operation. +func (s *IndicesStatsService) buildURL() (string, url.Values, error) { + var err error + var path string + if len(s.index) > 0 && len(s.metric) > 0 { + path, err = uritemplates.Expand("/{index}/_stats/{metric}", map[string]string{ + "index": strings.Join(s.index, ","), + "metric": strings.Join(s.metric, ","), + }) + } else if len(s.index) > 0 { + path, err = uritemplates.Expand("/{index}/_stats", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else if len(s.metric) > 0 { + path, err = uritemplates.Expand("/_stats/{metric}", map[string]string{ + "metric": strings.Join(s.metric, ","), + }) + } else { + path = "/_stats" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if len(s.groups) > 0 { + params.Set("groups", strings.Join(s.groups, ",")) + } + if s.level != "" { + params.Set("level", s.level) + } + if len(s.types) > 0 { + params.Set("types", strings.Join(s.types, ",")) + } + if len(s.completionFields) > 0 { + params.Set("completion_fields", strings.Join(s.completionFields, ",")) + } + if len(s.fielddataFields) > 0 { + params.Set("fielddata_fields", strings.Join(s.fielddataFields, ",")) + } + if len(s.fields) > 0 { + params.Set("fields", strings.Join(s.fields, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *IndicesStatsService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *IndicesStatsService) Do(ctx context.Context) (*IndicesStatsResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(IndicesStatsResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// IndicesStatsResponse is the response of IndicesStatsService.Do. +type IndicesStatsResponse struct { + // Shards provides information returned from shards. + Shards *ShardsInfo `json:"_shards"` + + // All provides summary stats about all indices. + All *IndexStats `json:"_all,omitempty"` + + // Indices provides a map into the stats of an index. The key of the + // map is the index name. + Indices map[string]*IndexStats `json:"indices,omitempty"` +} + +// IndexStats is index stats for a specific index. +type IndexStats struct { + UUID string `json:"uuid,omitempty"` + Primaries *IndexStatsDetails `json:"primaries,omitempty"` + Total *IndexStatsDetails `json:"total,omitempty"` + Shards map[string][]*IndexStatsDetails `json:"shards,omitempty"` +} + +type IndexStatsDetails struct { + Routing *IndexStatsRouting `json:"routing,omitempty"` + Docs *IndexStatsDocs `json:"docs,omitempty"` + Store *IndexStatsStore `json:"store,omitempty"` + Indexing *IndexStatsIndexing `json:"indexing,omitempty"` + Get *IndexStatsGet `json:"get,omitempty"` + Search *IndexStatsSearch `json:"search,omitempty"` + Merges *IndexStatsMerges `json:"merges,omitempty"` + Refresh *IndexStatsRefresh `json:"refresh,omitempty"` + Recovery *IndexStatsRecovery `json:"recovery,omitempty"` + Flush *IndexStatsFlush `json:"flush,omitempty"` + Warmer *IndexStatsWarmer `json:"warmer,omitempty"` + FilterCache *IndexStatsFilterCache `json:"filter_cache,omitempty"` + IdCache *IndexStatsIdCache `json:"id_cache,omitempty"` + Fielddata *IndexStatsFielddata `json:"fielddata,omitempty"` + Percolate *IndexStatsPercolate `json:"percolate,omitempty"` + Completion *IndexStatsCompletion `json:"completion,omitempty"` + Segments *IndexStatsSegments `json:"segments,omitempty"` + Translog *IndexStatsTranslog `json:"translog,omitempty"` + Suggest *IndexStatsSuggest `json:"suggest,omitempty"` + QueryCache *IndexStatsQueryCache `json:"query_cache,omitempty"` + RequestCache *IndexStatsRequestCache `json:"request_cache,omitempty"` + Commit *IndexStatsCommit `json:"commit,omitempty"` + SeqNo *IndexStatsSeqNo `json:"seq_no,omitempty"` + RetentionLeases *IndexStatsRetentionLeases `json:"retention_leases,omitempty"` + ShardPath *IndexStatsShardPath `json:"shard_path,omitempty"` +} + +type IndexStatsRouting struct { + State string `json:"state"` // e.g. "STARTED" + Primary bool `json:"primary"` + Node string `json:"node"` // e.g. "-aXnGv4oTW6bIIl0db3eCg" + RelocatingNode *string `json:"relocating_node"` +} + +type IndexStatsShardPath struct { + StatePath string `json:"state_path"` // e.g. "/usr/share/elasticsearch/data/nodes/0" + DataPath string `json:"data_path"` // e.g. "/usr/share/elasticsearch/data/nodes/0" + IsCustomDataPath bool `json:"is_custom_data_path"` +} + +type IndexStatsDocs struct { + Count int64 `json:"count,omitempty"` + Deleted int64 `json:"deleted,omitempty"` +} + +type IndexStatsStore struct { + Size string `json:"size,omitempty"` // human size, e.g. 119.3mb + SizeInBytes int64 `json:"size_in_bytes,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"` + IndexFailed int64 `json:"index_failed,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 { + Total int64 `json:"total,omitempty"` + GetTime string `json:"getTime,omitempty"` // 7.4.0 uses "getTime", earlier versions used "get_time" + TimeInMillis int64 `json:"time_in_millis,omitempty"` + ExistsTotal int64 `json:"exists_total,omitempty"` + ExistsTime string `json:"exists_time,omitempty"` + ExistsTimeInMillis int64 `json:"exists_time_in_millis,omitempty"` + MissingTotal int64 `json:"missing_total,omitempty"` + MissingTime string `json:"missing_time,omitempty"` + MissingTimeInMillis int64 `json:"missing_time_in_millis,omitempty"` + Current int64 `json:"current,omitempty"` +} + +type IndexStatsSearch struct { + OpenContexts int64 `json:"open_contexts,omitempty"` + QueryTotal int64 `json:"query_total,omitempty"` + QueryTime string `json:"query_time,omitempty"` + QueryTimeInMillis int64 `json:"query_time_in_millis,omitempty"` + QueryCurrent int64 `json:"query_current,omitempty"` + FetchTotal int64 `json:"fetch_total,omitempty"` + FetchTime string `json:"fetch_time,omitempty"` + FetchTimeInMillis int64 `json:"fetch_time_in_millis,omitempty"` + FetchCurrent int64 `json:"fetch_current,omitempty"` + ScrollTotal int64 `json:"scroll_total,omitempty"` + ScrollTime string `json:"scroll_time,omitempty"` + ScrollTimeInMillis int64 `json:"scroll_time_in_millis,omitempty"` + ScrollCurrent int64 `json:"scroll_current,omitempty"` + SuggestTotal int64 `json:"suggest_total,omitempty"` + SuggestTime string `json:"suggest_time,omitempty"` + SuggestTimeInMillis int64 `json:"suggest_time_in_millis,omitempty"` + SuggestCurrent int64 `json:"suggest_current,omitempty"` +} + +type IndexStatsMerges struct { + Current int64 `json:"current,omitempty"` + CurrentDocs int64 `json:"current_docs,omitempty"` + CurrentSize string `json:"current_size,omitempty"` + CurrentSizeInBytes int64 `json:"current_size_in_bytes,omitempty"` + Total int64 `json:"total,omitempty"` + TotalTime string `json:"total_time,omitempty"` + TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` + TotalDocs int64 `json:"total_docs,omitempty"` + TotalSize string `json:"total_size,omitempty"` + TotalSizeInBytes int64 `json:"total_size_in_bytes,omitempty"` + TotalStoppedTime string `json:"total_stopped_time,omitempty"` + TotalStoppedTimeInMillis int64 `json:"total_stopped_time_in_millis,omitempty"` + TotalThrottledTime string `json:"total_throttled_time,omitempty"` + TotalThrottledTimeInMillis int64 `json:"total_throttled_time_in_millis,omitempty"` + TotalAutoThrottle string `json:"total_auto_throttle,omitempty"` + TotalAutoThrottleInBytes int64 `json:"total_auto_throttle_in_bytes,omitempty"` +} + +type IndexStatsRefresh struct { + Total int64 `json:"total,omitempty"` + TotalTime string `json:"total_time,omitempty"` + TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` + ExternalTotal int64 `json:"external_total,omitempty"` + ExternalTotalTime string `json:"external_total_time,omitempty"` + ExternalTotalTimeInMillis int64 `json:"external_total_time_in_millis,omitempty"` + Listeners int64 `json:"listeners,omitempty"` +} + +type IndexStatsRecovery struct { + CurrentAsSource int64 `json:"current_as_source,omitempty"` + CurrentAsTarget int64 `json:"current_as_target,omitempty"` + ThrottleTime string `json:"throttle_time,omitempty"` + ThrottleTimeInMillis int64 `json:"throttle_time_in_millis,omitempty"` +} + +type IndexStatsFlush struct { + Total int64 `json:"total,omitempty"` + TotalTime string `json:"total_time,omitempty"` + TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` + Periodic int64 `json:"periodic,omitempty"` +} + +type IndexStatsWarmer struct { + Current int64 `json:"current,omitempty"` + Total int64 `json:"total,omitempty"` + TotalTime string `json:"total_time,omitempty"` + TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` +} + +type IndexStatsRequestCache struct { + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` + Evictions int64 `json:"evictions,omitempty"` + HitCount int64 `json:"hit_count,omitempty"` + MissCount int64 `json:"miss_count,omitempty"` +} + +type IndexStatsCommit struct { + ID string `json:"id,omitempty"` // lucene commit ID in base64, e.g. "m2tDMYHzSpSV6zJH0lIAnA==" + Generation int64 `json:"generation,omitempty"` + UserData map[string]string `json:"user_data,omitempty"` + NumDocs int64 `json:"num_docs,omitempty"` +} + +type IndexStatsFilterCache struct { + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` + Evictions int64 `json:"evictions,omitempty"` +} + +type IndexStatsIdCache struct { + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` +} + +type IndexStatsFielddata struct { + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` + Evictions int64 `json:"evictions,omitempty"` +} + +type IndexStatsPercolate struct { + Total int64 `json:"total,omitempty"` + GetTime string `json:"get_time,omitempty"` + TimeInMillis int64 `json:"time_in_millis,omitempty"` + Current int64 `json:"current,omitempty"` + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` + Queries int64 `json:"queries,omitempty"` +} + +type IndexStatsCompletion struct { + Size string `json:"size,omitempty"` + SizeInBytes int64 `json:"size_in_bytes,omitempty"` +} + +type IndexStatsSegments struct { + Count int64 `json:"count"` + Memory string `json:"memory"` // e.g. "61.3kb" + MemoryInBytes int64 `json:"memory_in_bytes"` + TermsMemory string `json:"terms_memory"` // e.g. "61.3kb" + TermsMemoryInBytes int64 `json:"terms_memory_in_bytes"` + StoredFieldsMemory string `json:"stored_fields_memory"` // e.g. "61.3kb" + StoredFieldsMemoryInBytes int64 `json:"stored_fields_memory_in_bytes"` + TermVectorsMemory string `json:"term_vectors_memory"` // e.g. "61.3kb" + TermVectorsMemoryInBytes int64 `json:"term_vectors_memory_in_bytes"` + NormsMemory string `json:"norms_memory"` // e.g. "61.3kb" + NormsMemoryInBytes int64 `json:"norms_memory_in_bytes"` + PointsMemory string `json:"points_memory"` // e.g. "61.3kb" + PointsMemoryInBytes int64 `json:"points_memory_in_bytes"` + DocValuesMemory string `json:"doc_values_memory"` // e.g. "61.3kb" + DocValuesMemoryInBytes int64 `json:"doc_values_memory_in_bytes"` + IndexWriterMemory string `json:"index_writer_memory"` // e.g. "61.3kb" + IndexWriterMemoryInBytes int64 `json:"index_writer_memory_in_bytes"` + VersionMapMemory string `json:"version_map_memory"` // e.g. "61.3kb" + VersionMapMemoryInBytes int64 `json:"version_map_memory_in_bytes"` + FixedBitSet string `json:"fixed_bit_set"` // e.g. "61.3kb" + FixedBitSetInBytes int64 `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int64 `json:"max_unsafe_auto_id_timestamp"` + FileSizes map[string]*ClusterStatsIndicesSegmentsFile `json:"file_sizes"` +} + +type IndexStatsTranslog struct { + Operations int64 `json:"operations,omitempty"` + Size string `json:"size,omitempty"` + SizeInBytes int64 `json:"size_in_bytes,omitempty"` + UncommittedOperations int64 `json:"uncommitted_operations,omitempty"` + UncommittedSize string `json:"uncommitted_size,omitempty"` + UncommittedSizeInBytes int64 `json:"uncommitted_size_in_bytes,omitempty"` + EarliestLastModifiedAge int64 `json:"earliest_last_modified_age,omitempty"` +} + +type IndexStatsSuggest struct { + Total int64 `json:"total,omitempty"` + Time string `json:"time,omitempty"` + TimeInMillis int64 `json:"time_in_millis,omitempty"` + Current int64 `json:"current,omitempty"` +} + +type IndexStatsQueryCache struct { + MemorySize string `json:"memory_size,omitempty"` + MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` + TotalCount int64 `json:"total_count,omitempty"` + HitCount int64 `json:"hit_count,omitempty"` + MissCount int64 `json:"miss_count,omitempty"` + CacheSize int64 `json:"cache_size,omitempty"` + CacheCount int64 `json:"cache_count,omitempty"` + Evictions int64 `json:"evictions,omitempty"` +} + +type IndexStatsSeqNo struct { + MaxSeqNo int64 `json:"max_seq_no,omitempty"` + LocalCheckpoint int64 `json:"local_checkpoint,omitempty"` + GlobalCheckpoint int64 `json:"global_checkpoint,omitempty"` +} + +type IndexStatsRetentionLeases struct { + PrimaryTerm int64 `json:"primary_term,omitempty"` + Version int64 `json:"version,omitempty"` + Leases []*IndexStatsRetentionLease `json:"leases,omitempty"` +} + +type IndexStatsRetentionLease struct { + Id string `json:"id,omitempty"` + RetainingSeqNo int64 `json:"retaining_seq_no,omitempty"` + Timestamp int64 `json:"timestamp,omitempty"` + Source string `json:"source,omitempty"` +} diff --git a/vendor/github.com/olivere/elastic/v7/indices_unfreeze.go b/vendor/github.com/olivere/elastic/v7/indices_unfreeze.go new file mode 100644 index 0000000..3da75d4 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/indices_unfreeze.go @@ -0,0 +1,229 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// IndicesUnfreezeService unfreezes an index. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/unfreeze-index-api.html +// and https://www.elastic.co/blog/creating-frozen-indices-with-the-elasticsearch-freeze-index-api +// for details. +type IndicesUnfreezeService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index string + timeout string + masterTimeout string + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string + waitForActiveShards string +} + +// NewIndicesUnfreezeService creates a new IndicesUnfreezeService. +func NewIndicesUnfreezeService(client *Client) *IndicesUnfreezeService { + return &IndicesUnfreezeService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IndicesUnfreezeService) Pretty(pretty bool) *IndicesUnfreezeService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IndicesUnfreezeService) Human(human bool) *IndicesUnfreezeService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IndicesUnfreezeService) ErrorTrace(errorTrace bool) *IndicesUnfreezeService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IndicesUnfreezeService) FilterPath(filterPath ...string) *IndicesUnfreezeService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IndicesUnfreezeService) Header(name string, value string) *IndicesUnfreezeService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IndicesUnfreezeService) Headers(headers http.Header) *IndicesUnfreezeService { + s.headers = headers + return s +} + +// Index is the name of the index to unfreeze. +func (s *IndicesUnfreezeService) Index(index string) *IndicesUnfreezeService { + s.index = index + return s +} + +// Timeout allows to specify an explicit timeout. +func (s *IndicesUnfreezeService) Timeout(timeout string) *IndicesUnfreezeService { + s.timeout = timeout + return s +} + +// MasterTimeout allows to specify a timeout for connection to master. +func (s *IndicesUnfreezeService) MasterTimeout(masterTimeout string) *IndicesUnfreezeService { + s.masterTimeout = masterTimeout + return s +} + +// IgnoreUnavailable indicates whether specified concrete indices should be +// ignored when unavailable (missing or closed). +func (s *IndicesUnfreezeService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesUnfreezeService { + 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 *IndicesUnfreezeService) AllowNoIndices(allowNoIndices bool) *IndicesUnfreezeService { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards specifies whether to expand wildcard expression to +// concrete indices that are open, closed or both.. +func (s *IndicesUnfreezeService) ExpandWildcards(expandWildcards string) *IndicesUnfreezeService { + s.expandWildcards = expandWildcards + return s +} + +// WaitForActiveShards sets the number of active shards to wait for +// before the operation returns. +func (s *IndicesUnfreezeService) WaitForActiveShards(numShards string) *IndicesUnfreezeService { + s.waitForActiveShards = numShards + return s +} + +// buildURL builds the URL for the operation. +func (s *IndicesUnfreezeService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/{index}/_unfreeze", map[string]string{ + "index": s.index, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if s.expandWildcards != "" { + params.Set("expand_wildcards", s.expandWildcards) + } + if s.ignoreUnavailable != nil { + params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) + } + 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.waitForActiveShards != "" { + params.Set("wait_for_active_shards", s.waitForActiveShards) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *IndicesUnfreezeService) Validate() error { + var invalid []string + if s.index == "" { + invalid = append(invalid, "Index") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the service. +func (s *IndicesUnfreezeService) Do(ctx context.Context) (*IndicesUnfreezeResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(IndicesUnfreezeResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// IndicesUnfreezeResponse is the outcome of freezing an index. +type IndicesUnfreezeResponse struct { + Shards *ShardsInfo `json:"_shards"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/ingest_delete_pipeline.go b/vendor/github.com/olivere/elastic/v7/ingest_delete_pipeline.go similarity index 60% rename from vendor/gopkg.in/olivere/elastic.v6/ingest_delete_pipeline.go rename to vendor/github.com/olivere/elastic/v7/ingest_delete_pipeline.go index 7ca2802..fed06d6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/ingest_delete_pipeline.go +++ b/vendor/github.com/olivere/elastic/v7/ingest_delete_pipeline.go @@ -8,16 +8,24 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IngestDeletePipelineService deletes pipelines by ID. -// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.2/delete-pipeline-api.html. +// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/delete-pipeline-api.html. type IngestDeletePipelineService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string masterTimeout string timeout string @@ -30,6 +38,46 @@ func NewIngestDeletePipelineService(client *Client) *IngestDeletePipelineService } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IngestDeletePipelineService) Pretty(pretty bool) *IngestDeletePipelineService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IngestDeletePipelineService) Human(human bool) *IngestDeletePipelineService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IngestDeletePipelineService) ErrorTrace(errorTrace bool) *IngestDeletePipelineService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IngestDeletePipelineService) FilterPath(filterPath ...string) *IngestDeletePipelineService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IngestDeletePipelineService) Header(name string, value string) *IngestDeletePipelineService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IngestDeletePipelineService) Headers(headers http.Header) *IngestDeletePipelineService { + s.headers = headers + return s +} + // Id is documented as: Pipeline ID. func (s *IngestDeletePipelineService) Id(id string) *IngestDeletePipelineService { s.id = id @@ -48,12 +96,6 @@ func (s *IngestDeletePipelineService) Timeout(timeout string) *IngestDeletePipel return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IngestDeletePipelineService) Pretty(pretty bool) *IngestDeletePipelineService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IngestDeletePipelineService) buildURL() (string, url.Values, error) { // Build URL @@ -66,8 +108,17 @@ func (s *IngestDeletePipelineService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -105,9 +156,10 @@ func (s *IngestDeletePipelineService) Do(ctx context.Context) (*IngestDeletePipe // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "DELETE", - Path: path, - Params: params, + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/ingest_get_pipeline.go b/vendor/github.com/olivere/elastic/v7/ingest_get_pipeline.go similarity index 52% rename from vendor/gopkg.in/olivere/elastic.v6/ingest_get_pipeline.go rename to vendor/github.com/olivere/elastic/v7/ingest_get_pipeline.go index 46d28bd..5f7e027 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/ingest_get_pipeline.go +++ b/vendor/github.com/olivere/elastic/v7/ingest_get_pipeline.go @@ -7,18 +7,26 @@ package elastic import ( "context" "encoding/json" + "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IngestGetPipelineService returns pipelines based on ID. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/get-pipeline-api.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/get-pipeline-api.html // for documentation. type IngestGetPipelineService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id []string masterTimeout string } @@ -30,6 +38,46 @@ func NewIngestGetPipelineService(client *Client) *IngestGetPipelineService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IngestGetPipelineService) Pretty(pretty bool) *IngestGetPipelineService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IngestGetPipelineService) Human(human bool) *IngestGetPipelineService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IngestGetPipelineService) ErrorTrace(errorTrace bool) *IngestGetPipelineService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IngestGetPipelineService) FilterPath(filterPath ...string) *IngestGetPipelineService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IngestGetPipelineService) Header(name string, value string) *IngestGetPipelineService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IngestGetPipelineService) Headers(headers http.Header) *IngestGetPipelineService { + s.headers = headers + return s +} + // Id is a list of pipeline ids. Wildcards supported. func (s *IngestGetPipelineService) Id(id ...string) *IngestGetPipelineService { s.id = append(s.id, id...) @@ -42,12 +90,6 @@ func (s *IngestGetPipelineService) MasterTimeout(masterTimeout string) *IngestGe return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IngestGetPipelineService) Pretty(pretty bool) *IngestGetPipelineService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *IngestGetPipelineService) buildURL() (string, url.Values, error) { var err error @@ -67,8 +109,17 @@ func (s *IngestGetPipelineService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -96,9 +147,10 @@ func (s *IngestGetPipelineService) Do(ctx context.Context) (IngestGetPipelineRes // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -115,7 +167,11 @@ func (s *IngestGetPipelineService) Do(ctx context.Context) (IngestGetPipelineRes // IngestGetPipelineResponse is the response of IngestGetPipelineService.Do. type IngestGetPipelineResponse map[string]*IngestGetPipeline +// IngestGetPipeline describes a specific ingest pipeline, its +// processors etc. type IngestGetPipeline struct { - ID string `json:"id"` - Config map[string]interface{} `json:"config"` + Description string `json:"description"` + Processors []map[string]interface{} `json:"processors"` + Version int64 `json:"version,omitempty"` + OnFailure []map[string]interface{} `json:"on_failure,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/ingest_put_pipeline.go b/vendor/github.com/olivere/elastic/v7/ingest_put_pipeline.go similarity index 64% rename from vendor/gopkg.in/olivere/elastic.v6/ingest_put_pipeline.go rename to vendor/github.com/olivere/elastic/v7/ingest_put_pipeline.go index 7c1dbc4..5f780f6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/ingest_put_pipeline.go +++ b/vendor/github.com/olivere/elastic/v7/ingest_put_pipeline.go @@ -8,18 +8,26 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // IngestPutPipelineService adds pipelines and updates existing pipelines in // the cluster. // -// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.2/put-pipeline-api.html. +// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/put-pipeline-api.html. type IngestPutPipelineService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string masterTimeout string timeout string @@ -34,6 +42,46 @@ func NewIngestPutPipelineService(client *Client) *IngestPutPipelineService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IngestPutPipelineService) Pretty(pretty bool) *IngestPutPipelineService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IngestPutPipelineService) Human(human bool) *IngestPutPipelineService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IngestPutPipelineService) ErrorTrace(errorTrace bool) *IngestPutPipelineService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IngestPutPipelineService) FilterPath(filterPath ...string) *IngestPutPipelineService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IngestPutPipelineService) Header(name string, value string) *IngestPutPipelineService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IngestPutPipelineService) Headers(headers http.Header) *IngestPutPipelineService { + s.headers = headers + return s +} + // Id is the pipeline ID. func (s *IngestPutPipelineService) Id(id string) *IngestPutPipelineService { s.id = id @@ -52,12 +100,6 @@ func (s *IngestPutPipelineService) Timeout(timeout string) *IngestPutPipelineSer return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IngestPutPipelineService) Pretty(pretty bool) *IngestPutPipelineService { - s.pretty = pretty - return s -} - // BodyJson is the ingest definition, defined as a JSON-serializable document. // Use e.g. a map[string]interface{} here. func (s *IngestPutPipelineService) BodyJson(body interface{}) *IngestPutPipelineService { @@ -83,8 +125,17 @@ func (s *IngestPutPipelineService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -133,10 +184,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/ingest_simulate_pipeline.go b/vendor/github.com/olivere/elastic/v7/ingest_simulate_pipeline.go similarity index 63% rename from vendor/gopkg.in/olivere/elastic.v6/ingest_simulate_pipeline.go rename to vendor/github.com/olivere/elastic/v7/ingest_simulate_pipeline.go index 43cca20..70de000 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/ingest_simulate_pipeline.go +++ b/vendor/github.com/olivere/elastic/v7/ingest_simulate_pipeline.go @@ -8,19 +8,27 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/simulate-pipeline-api.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/simulate-pipeline-api.html. type IngestSimulatePipelineService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string verbose *bool bodyJson interface{} @@ -34,6 +42,46 @@ func NewIngestSimulatePipelineService(client *Client) *IngestSimulatePipelineSer } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *IngestSimulatePipelineService) Pretty(pretty bool) *IngestSimulatePipelineService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *IngestSimulatePipelineService) Human(human bool) *IngestSimulatePipelineService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *IngestSimulatePipelineService) ErrorTrace(errorTrace bool) *IngestSimulatePipelineService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *IngestSimulatePipelineService) FilterPath(filterPath ...string) *IngestSimulatePipelineService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *IngestSimulatePipelineService) Header(name string, value string) *IngestSimulatePipelineService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *IngestSimulatePipelineService) Headers(headers http.Header) *IngestSimulatePipelineService { + s.headers = headers + return s +} + // Id specifies the pipeline ID. func (s *IngestSimulatePipelineService) Id(id string) *IngestSimulatePipelineService { s.id = id @@ -46,12 +94,6 @@ func (s *IngestSimulatePipelineService) Verbose(verbose bool) *IngestSimulatePip return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *IngestSimulatePipelineService) Pretty(pretty bool) *IngestSimulatePipelineService { - s.pretty = pretty - return s -} - // BodyJson is the ingest definition, defined as a JSON-serializable simulate // definition. Use e.g. a map[string]interface{} here. func (s *IngestSimulatePipelineService) BodyJson(body interface{}) *IngestSimulatePipelineService { @@ -84,11 +126,20 @@ func (s *IngestSimulatePipelineService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } - if s.verbose != nil { - params.Set("verbose", fmt.Sprintf("%v", *s.verbose)) + if v := s.verbose; v != nil { + params.Set("verbose", fmt.Sprint(*v)) } return path, params, nil } @@ -128,10 +179,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/inner_hit.go b/vendor/github.com/olivere/elastic/v7/inner_hit.go similarity index 89% rename from vendor/gopkg.in/olivere/elastic.v6/inner_hit.go rename to vendor/github.com/olivere/elastic/v7/inner_hit.go index c371fbf..8036626 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/inner_hit.go +++ b/vendor/github.com/olivere/elastic/v7/inner_hit.go @@ -7,7 +7,7 @@ package elastic // InnerHit implements a simple join for parent/child, nested, and even // top-level documents in Elasticsearch. // It is an experimental feature for Elasticsearch versions 1.5 (or greater). -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-inner-hits.html +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-inner-hits.html // for documentation. // // See the tests for SearchSource, HasChildFilter, HasChildQuery, @@ -96,11 +96,21 @@ func (hit *InnerHit) DocvalueFields(docvalueFields ...string) *InnerHit { return hit } +func (hit *InnerHit) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *InnerHit { + hit.source.DocvalueFieldsWithFormat(docvalueFields...) + return hit +} + func (hit *InnerHit) DocvalueField(docvalueField string) *InnerHit { hit.source.DocvalueField(docvalueField) return hit } +func (hit *InnerHit) DocvalueFieldWithFormat(docvalueField DocvalueField) *InnerHit { + hit.source.DocvalueFieldWithFormat(docvalueField) + return hit +} + func (hit *InnerHit) ScriptFields(scriptFields ...*ScriptField) *InnerHit { hit.source.ScriptFields(scriptFields...) return hit diff --git a/vendor/gopkg.in/olivere/elastic.v6/logger.go b/vendor/github.com/olivere/elastic/v7/logger.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/logger.go rename to vendor/github.com/olivere/elastic/v7/logger.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/mget.go b/vendor/github.com/olivere/elastic/v7/mget.go similarity index 75% rename from vendor/gopkg.in/olivere/elastic.v6/mget.go rename to vendor/github.com/olivere/elastic/v7/mget.go index eccf194..9e5f83b 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/mget.go +++ b/vendor/github.com/olivere/elastic/v7/mget.go @@ -7,6 +7,7 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" ) @@ -16,11 +17,17 @@ 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.2/docs-multi-get.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-multi-get.html // for details. type MgetService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + preference string realtime *bool refresh string @@ -37,6 +44,46 @@ func NewMgetService(client *Client) *MgetService { return builder } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *MgetService) Pretty(pretty bool) *MgetService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *MgetService) Human(human bool) *MgetService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *MgetService) ErrorTrace(errorTrace bool) *MgetService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *MgetService) FilterPath(filterPath ...string) *MgetService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *MgetService) Header(name string, value string) *MgetService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *MgetService) Headers(headers http.Header) *MgetService { + s.headers = headers + return s +} + // Preference specifies the node or shard the operation should be performed // on (default: random). func (s *MgetService) Preference(preference string) *MgetService { @@ -46,7 +93,7 @@ func (s *MgetService) Preference(preference string) *MgetService { // Refresh the shard containing the document before performing the operation. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *MgetService) Refresh(refresh string) *MgetService { s.refresh = refresh @@ -71,12 +118,6 @@ func (s *MgetService) StoredFields(storedFields ...string) *MgetService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *MgetService) Pretty(pretty bool) *MgetService { - s.pretty = pretty - return s -} - // Add an item to the request. func (s *MgetService) Add(items ...*MultiGetItem) *MgetService { s.items = append(s.items, items...) @@ -103,7 +144,19 @@ func (s *MgetService) Do(ctx context.Context) (*MgetResponse, error) { // Build url path := "/_mget" - params := make(url.Values) + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } if s.realtime != nil { params.Add("realtime", fmt.Sprintf("%v", *s.realtime)) } @@ -128,10 +181,11 @@ 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, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -237,7 +291,7 @@ func (item *MultiGetItem) Source() (interface{}, error) { source["_source"] = src } if item.routing != "" { - source["_routing"] = item.routing + source["routing"] = item.routing } if len(item.storedFields) > 0 { source["stored_fields"] = strings.Join(item.storedFields, ",") diff --git a/vendor/gopkg.in/olivere/elastic.v6/msearch.go b/vendor/github.com/olivere/elastic/v7/msearch.go similarity index 55% rename from vendor/gopkg.in/olivere/elastic.v6/msearch.go rename to vendor/github.com/olivere/elastic/v7/msearch.go index c1a589a..1f6aed0 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/msearch.go +++ b/vendor/github.com/olivere/elastic/v7/msearch.go @@ -8,16 +8,23 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" ) // MultiSearch executes one or more searches in one roundtrip. type MultiSearchService struct { - client *Client + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + requests []*SearchRequest indices []string - pretty bool maxConcurrentRequests *int preFilterShardSize *int } @@ -29,6 +36,46 @@ func NewMultiSearchService(client *Client) *MultiSearchService { return builder } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *MultiSearchService) Pretty(pretty bool) *MultiSearchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *MultiSearchService) Human(human bool) *MultiSearchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *MultiSearchService) ErrorTrace(errorTrace bool) *MultiSearchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *MultiSearchService) FilterPath(filterPath ...string) *MultiSearchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *MultiSearchService) Header(name string, value string) *MultiSearchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *MultiSearchService) Headers(headers http.Header) *MultiSearchService { + s.headers = headers + return s +} + func (s *MultiSearchService) Add(requests ...*SearchRequest) *MultiSearchService { s.requests = append(s.requests, requests...) return s @@ -39,11 +86,6 @@ func (s *MultiSearchService) Index(indices ...string) *MultiSearchService { return s } -func (s *MultiSearchService) Pretty(pretty bool) *MultiSearchService { - s.pretty = pretty - return s -} - func (s *MultiSearchService) MaxConcurrentSearches(max int) *MultiSearchService { s.maxConcurrentRequests = &max return s @@ -59,9 +101,18 @@ func (s *MultiSearchService) Do(ctx context.Context) (*MultiSearchResult, error) path := "/_msearch" // Parameters - params := make(url.Values) - if s.pretty { - params.Set("pretty", fmt.Sprintf("%v", s.pretty)) + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if v := s.maxConcurrentRequests; v != nil { params.Set("max_concurrent_searches", fmt.Sprintf("%v", *v)) @@ -93,10 +144,11 @@ func (s *MultiSearchService) Do(ctx context.Context) (*MultiSearchResult, error) // Get response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, - Body: body, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -112,5 +164,6 @@ func (s *MultiSearchService) Do(ctx context.Context) (*MultiSearchResult, error) // MultiSearchResult is the outcome of running a multi-search operation. type MultiSearchResult struct { - Responses []*SearchResult `json:"responses,omitempty"` + TookInMillis int64 `json:"took,omitempty"` // search time in milliseconds + Responses []*SearchResult `json:"responses,omitempty"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/mtermvectors.go b/vendor/github.com/olivere/elastic/v7/mtermvectors.go similarity index 86% rename from vendor/gopkg.in/olivere/elastic.v6/mtermvectors.go rename to vendor/github.com/olivere/elastic/v7/mtermvectors.go index e8fb48f..59284e6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/mtermvectors.go +++ b/vendor/github.com/olivere/elastic/v7/mtermvectors.go @@ -8,21 +8,28 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/docs-multi-termvectors.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-multi-termvectors.html // for documentation. type MultiTermvectorService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index string typ string fieldStatistics *bool @@ -50,9 +57,43 @@ func NewMultiTermvectorService(client *Client) *MultiTermvectorService { } } -// Pretty indicates that the JSON response be indented and human readable. +// Pretty tells Elasticsearch whether to return a formatted JSON response. func (s *MultiTermvectorService) Pretty(pretty bool) *MultiTermvectorService { - s.pretty = pretty + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *MultiTermvectorService) Human(human bool) *MultiTermvectorService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *MultiTermvectorService) ErrorTrace(errorTrace bool) *MultiTermvectorService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *MultiTermvectorService) FilterPath(filterPath ...string) *MultiTermvectorService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *MultiTermvectorService) Header(name string, value string) *MultiTermvectorService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *MultiTermvectorService) Headers(headers http.Header) *MultiTermvectorService { + s.headers = headers return s } @@ -197,8 +238,17 @@ func (s *MultiTermvectorService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.fieldStatistics != nil { params.Set("field_statistics", fmt.Sprintf("%v", *s.fieldStatistics)) @@ -279,10 +329,11 @@ 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, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/nodes_info.go b/vendor/github.com/olivere/elastic/v7/nodes_info.go similarity index 86% rename from vendor/gopkg.in/olivere/elastic.v6/nodes_info.go rename to vendor/github.com/olivere/elastic/v7/nodes_info.go index 6323481..3037df4 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/nodes_info.go +++ b/vendor/github.com/olivere/elastic/v7/nodes_info.go @@ -7,34 +7,78 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" "time" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/cluster-nodes-info.html. +// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-nodes-info.html. type NodesInfoService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + nodeId []string metric []string flatSettings *bool - human *bool } // NewNodesInfoService creates a new NodesInfoService. func NewNodesInfoService(client *Client) *NodesInfoService { return &NodesInfoService{ client: client, - nodeId: []string{"_all"}, - metric: []string{"_all"}, } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *NodesInfoService) Pretty(pretty bool) *NodesInfoService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *NodesInfoService) Human(human bool) *NodesInfoService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *NodesInfoService) ErrorTrace(errorTrace bool) *NodesInfoService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *NodesInfoService) FilterPath(filterPath ...string) *NodesInfoService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *NodesInfoService) Header(name string, value string) *NodesInfoService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *NodesInfoService) Headers(headers http.Header) *NodesInfoService { + s.headers = headers + return s +} + // NodeId is a list of node IDs or names to limit the returned information. // Use "_local" to return information from the node you're connecting to, // leave empty to get information from all nodes. @@ -57,24 +101,26 @@ func (s *NodesInfoService) FlatSettings(flatSettings bool) *NodesInfoService { return s } -// Human indicates whether to return time and byte values in human-readable format. -func (s *NodesInfoService) Human(human bool) *NodesInfoService { - s.human = &human - return s -} - -// Pretty indicates whether to indent the returned JSON. -func (s *NodesInfoService) Pretty(pretty bool) *NodesInfoService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *NodesInfoService) buildURL() (string, url.Values, error) { + var nodeId, metric string + + if len(s.nodeId) > 0 { + nodeId = strings.Join(s.nodeId, ",") + } else { + nodeId = "_all" + } + + if len(s.metric) > 0 { + metric = strings.Join(s.metric, ",") + } else { + metric = "_all" + } + // Build URL path, err := uritemplates.Expand("/_nodes/{node_id}/{metric}", map[string]string{ - "node_id": strings.Join(s.nodeId, ","), - "metric": strings.Join(s.metric, ","), + "node_id": nodeId, + "metric": metric, }) if err != nil { return "", url.Values{}, err @@ -82,14 +128,20 @@ func (s *NodesInfoService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.flatSettings != nil { - params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings)) + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } - if s.pretty { - params.Set("pretty", "true") + if s.flatSettings != nil { + params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings)) } return path, params, nil } @@ -114,9 +166,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/nodes_stats.go b/vendor/github.com/olivere/elastic/v7/nodes_stats.go similarity index 89% rename from vendor/gopkg.in/olivere/elastic.v6/nodes_stats.go rename to vendor/github.com/olivere/elastic/v7/nodes_stats.go index 7c5f0c9..a57651e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/nodes_stats.go +++ b/vendor/github.com/olivere/elastic/v7/nodes_stats.go @@ -8,18 +8,25 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // NodesStatsService returns node statistics. -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-nodes-stats.html +// See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-nodes-stats.html // for details. type NodesStatsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + metric []string indexMetric []string nodeId []string @@ -27,7 +34,6 @@ type NodesStatsService struct { fielddataFields []string fields []string groups *bool - human *bool level string timeout string types []string @@ -40,6 +46,46 @@ func NewNodesStatsService(client *Client) *NodesStatsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *NodesStatsService) Pretty(pretty bool) *NodesStatsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *NodesStatsService) Human(human bool) *NodesStatsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *NodesStatsService) ErrorTrace(errorTrace bool) *NodesStatsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *NodesStatsService) FilterPath(filterPath ...string) *NodesStatsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *NodesStatsService) Header(name string, value string) *NodesStatsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *NodesStatsService) Headers(headers http.Header) *NodesStatsService { + s.headers = headers + return s +} + // Metric limits the information returned to the specified metrics. func (s *NodesStatsService) Metric(metric ...string) *NodesStatsService { s.metric = append(s.metric, metric...) @@ -87,12 +133,6 @@ func (s *NodesStatsService) Groups(groups bool) *NodesStatsService { return s } -// Human indicates whether to return time and byte values in human-readable format. -func (s *NodesStatsService) Human(human bool) *NodesStatsService { - s.human = &human - return s -} - // Level specifies whether to return indices stats aggregated at node, index or shard level. func (s *NodesStatsService) Level(level string) *NodesStatsService { s.level = level @@ -111,12 +151,6 @@ func (s *NodesStatsService) Types(types ...string) *NodesStatsService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *NodesStatsService) Pretty(pretty bool) *NodesStatsService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *NodesStatsService) buildURL() (string, url.Values, error) { var err error @@ -164,8 +198,17 @@ func (s *NodesStatsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if len(s.completionFields) > 0 { params.Set("completion_fields", strings.Join(s.completionFields, ",")) @@ -179,9 +222,6 @@ func (s *NodesStatsService) buildURL() (string, url.Values, error) { if s.groups != nil { params.Set("groups", fmt.Sprintf("%v", *s.groups)) } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) - } if s.level != "" { params.Set("level", s.level) } @@ -214,9 +254,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -325,16 +366,19 @@ type NodesStatsStoreStats struct { } 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"` + ThrottledTime string `json:"throttle_time"` // no typo, see https://github.com/elastic/elasticsearch/blob/ff99bc1d3f8a7ea72718872d214ec2097dfca276/server/src/main/java/org/elasticsearch/index/shard/IndexingStats.java#L244 + ThrottledTimeInMillis int64 `json:"throttle_time_in_millis"` Types map[string]*NodesStatsIndexingStats `json:"types"` // stats for individual types } diff --git a/vendor/github.com/olivere/elastic/v7/ping.go b/vendor/github.com/olivere/elastic/v7/ping.go new file mode 100644 index 0000000..1ad7861 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/ping.go @@ -0,0 +1,197 @@ +// 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/http" + "net/url" + "strings" +) + +// PingService checks if an Elasticsearch server on a given URL is alive. +// When asked for, it can also return various information about the +// Elasticsearch server, e.g. the Elasticsearch version number. +// +// Ping simply starts a HTTP GET request to the URL of the server. +// If the server responds with HTTP Status code 200 OK, the server is alive. +type PingService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + url string + timeout string + httpHeadOnly bool +} + +// PingResult is the result returned from querying the Elasticsearch server. +type PingResult struct { + Name string `json:"name"` + ClusterName string `json:"cluster_name"` + Version struct { + Number string `json:"number"` // e.g. "7.0.0" + BuildFlavor string `json:"build_flavor"` // e.g. "oss" or "default" + BuildType string `json:"build_type"` // e.g. "docker" + BuildHash string `json:"build_hash"` // e.g. "b7e28a7" + BuildDate string `json:"build_date"` // e.g. "2019-04-05T22:55:32.697037Z" + BuildSnapshot bool `json:"build_snapshot"` // e.g. false + LuceneVersion string `json:"lucene_version"` // e.g. "8.0.0" + MinimumWireCompatibilityVersion string `json:"minimum_wire_compatibility_version"` // e.g. "6.7.0" + MinimumIndexCompatibilityVersion string `json:"minimum_index_compatibility_version"` // e.g. "6.0.0-beta1" + } `json:"version"` + TagLine string `json:"tagline"` +} + +func NewPingService(client *Client) *PingService { + return &PingService{ + client: client, + url: DefaultURL, + httpHeadOnly: false, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *PingService) Pretty(pretty bool) *PingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *PingService) Human(human bool) *PingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *PingService) ErrorTrace(errorTrace bool) *PingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *PingService) FilterPath(filterPath ...string) *PingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *PingService) Header(name string, value string) *PingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *PingService) Headers(headers http.Header) *PingService { + s.headers = headers + return s +} + +func (s *PingService) URL(url string) *PingService { + s.url = url + return s +} + +func (s *PingService) Timeout(timeout string) *PingService { + s.timeout = timeout + return s +} + +// HeadOnly makes the service to only return the status code in Do; +// the PingResult will be nil. +func (s *PingService) HttpHeadOnly(httpHeadOnly bool) *PingService { + s.httpHeadOnly = httpHeadOnly + return s +} + +// Do returns the PingResult, the HTTP status code of the Elasticsearch +// server, and an error. +func (s *PingService) Do(ctx context.Context) (*PingResult, int, error) { + s.client.mu.RLock() + basicAuth := s.client.basicAuth + basicAuthUsername := s.client.basicAuthUsername + basicAuthPassword := s.client.basicAuthPassword + defaultHeaders := s.client.headers + s.client.mu.RUnlock() + + url_ := strings.TrimSuffix(s.url, "/") + "/" + + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if len(params) > 0 { + url_ += "?" + params.Encode() + } + + var method string + if s.httpHeadOnly { + method = "HEAD" + } else { + method = "GET" + } + + // Notice: This service must NOT use PerformRequest! + req, err := NewRequest(method, url_) + if err != nil { + return nil, 0, err + } + if len(s.headers) > 0 { + for key, values := range s.headers { + for _, v := range values { + req.Header.Add(key, v) + } + } + } + if len(defaultHeaders) > 0 { + for key, values := range defaultHeaders { + for _, v := range values { + req.Header.Add(key, v) + } + } + } + + if basicAuth { + req.SetBasicAuth(basicAuthUsername, basicAuthPassword) + } + + res, err := s.client.c.Do((*http.Request)(req).WithContext(ctx)) + if err != nil { + return nil, 0, err + } + defer res.Body.Close() + + var ret *PingResult + if !s.httpHeadOnly { + ret = new(PingResult) + if err := json.NewDecoder(res.Body).Decode(ret); err != nil { + return nil, res.StatusCode, err + } + } + + return ret, res.StatusCode, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/plugins.go b/vendor/github.com/olivere/elastic/v7/plugins.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/plugins.go rename to vendor/github.com/olivere/elastic/v7/plugins.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/query.go b/vendor/github.com/olivere/elastic/v7/query.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/query.go rename to vendor/github.com/olivere/elastic/v7/query.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/reindex.go b/vendor/github.com/olivere/elastic/v7/reindex.go similarity index 75% rename from vendor/gopkg.in/olivere/elastic.v6/reindex.go rename to vendor/github.com/olivere/elastic/v7/reindex.go index e908cf5..2bf74a6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/reindex.go +++ b/vendor/github.com/olivere/elastic/v7/reindex.go @@ -6,15 +6,24 @@ package elastic import ( "context" + "errors" "fmt" + "net/http" "net/url" + "strings" ) // 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.2/docs-reindex.html. +// It is documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-reindex.html. type ReindexService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + refresh string timeout string waitForActiveShards string @@ -36,6 +45,46 @@ func NewReindexService(client *Client) *ReindexService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ReindexService) Pretty(pretty bool) *ReindexService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ReindexService) Human(human bool) *ReindexService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ReindexService) ErrorTrace(errorTrace bool) *ReindexService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ReindexService) FilterPath(filterPath ...string) *ReindexService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ReindexService) Header(name string, value string) *ReindexService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ReindexService) Headers(headers http.Header) *ReindexService { + s.headers = headers + return s +} + // WaitForActiveShards sets the number of shard copies that must be active before // proceeding with the reindex operation. Defaults to 1, meaning the primary shard only. // Set to `all` for all shard copies, otherwise set to any non-negative value less than or @@ -53,9 +102,9 @@ func (s *ReindexService) RequestsPerSecond(requestsPerSecond int) *ReindexServic } // Slices specifies the number of slices this task should be divided into. Defaults to 1. -// It used to be a number, but can be set to "auto" as of 6.3. +// It used to be a number, but can be set to "auto" as of 6.7. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/docs-reindex.html#docs-reindex-slice +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-reindex.html#docs-reindex-slice // for details. func (s *ReindexService) Slices(slices interface{}) *ReindexService { s.slices = slices @@ -65,7 +114,7 @@ func (s *ReindexService) Slices(slices interface{}) *ReindexService { // Refresh indicates whether Elasticsearch should refresh the effected indexes // immediately. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *ReindexService) Refresh(refresh string) *ReindexService { s.refresh = refresh @@ -86,12 +135,6 @@ func (s *ReindexService) WaitForCompletion(waitForCompletion bool) *ReindexServi return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *ReindexService) Pretty(pretty bool) *ReindexService { - s.pretty = pretty - return s -} - // Source specifies the source of the reindexing process. func (s *ReindexService) Source(source *ReindexSource) *ReindexService { s.source = source @@ -181,8 +224,17 @@ func (s *ReindexService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.refresh != "" { params.Set("refresh", s.refresh) @@ -214,7 +266,7 @@ func (s *ReindexService) Validate() error { if s.source == nil { invalid = append(invalid, "Source") } else { - if len(s.source.indices) == 0 { + if len(s.source.request.indices) == 0 { invalid = append(invalid, "Source.Index") } } @@ -285,10 +337,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -299,6 +352,7 @@ func (s *ReindexService) Do(ctx context.Context) (*BulkIndexByScrollResponse, er if err := s.client.decoder.Decode(res.Body, ret); err != nil { return nil, err } + ret.Header = res.Header return ret, nil } @@ -311,7 +365,7 @@ func (s *ReindexService) DoAsync(ctx context.Context) (*StartTaskResult, error) return nil, err } - // DoAsync only makes sense with WaitForCompletion set to true + // DoAsync only makes sense with WaitForCompletion set to false if s.waitForCompletion != nil && *s.waitForCompletion { return nil, fmt.Errorf("cannot start a task with WaitForCompletion set to true") } @@ -332,10 +386,11 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -346,6 +401,7 @@ func (s *ReindexService) DoAsync(ctx context.Context) (*StartTaskResult, error) if err := s.client.decoder.Decode(res.Body, ret); err != nil { return nil, err } + ret.Header = res.Header return ret, nil } @@ -353,85 +409,111 @@ 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" - indices []string - types []string - routing *string - preference *string - requestCache *bool - scroll string - query Query - sorts []SortInfo - sorters []Sorter - searchSource *SearchSource - remoteInfo *ReindexRemoteInfo + request *SearchRequest + remoteInfo *ReindexRemoteInfo } // NewReindexSource creates a new ReindexSource. func NewReindexSource() *ReindexSource { - return &ReindexSource{} + return &ReindexSource{ + request: NewSearchRequest(), + } +} + +// Request specifies the search request used for source. +func (r *ReindexSource) Request(request *SearchRequest) *ReindexSource { + if request == nil { + r.request = NewSearchRequest() + } else { + r.request = request + } + return r } // SearchType is the search operation type. Possible values are // "query_then_fetch" and "dfs_query_then_fetch". func (r *ReindexSource) SearchType(searchType string) *ReindexSource { - r.searchType = searchType + r.request = r.request.SearchType(searchType) return r } func (r *ReindexSource) SearchTypeDfsQueryThenFetch() *ReindexSource { - return r.SearchType("dfs_query_then_fetch") + r.request = r.request.SearchType("dfs_query_then_fetch") + return r } func (r *ReindexSource) SearchTypeQueryThenFetch() *ReindexSource { - return r.SearchType("query_then_fetch") + r.request = r.request.SearchType("query_then_fetch") + return r } func (r *ReindexSource) Index(indices ...string) *ReindexSource { - r.indices = append(r.indices, indices...) + r.request = r.request.Index(indices...) return r } func (r *ReindexSource) Type(types ...string) *ReindexSource { - r.types = append(r.types, types...) + r.request = r.request.Type(types...) return r } func (r *ReindexSource) Preference(preference string) *ReindexSource { - r.preference = &preference + r.request = r.request.Preference(preference) return r } func (r *ReindexSource) RequestCache(requestCache bool) *ReindexSource { - r.requestCache = &requestCache + r.request = r.request.RequestCache(requestCache) return r } func (r *ReindexSource) Scroll(scroll string) *ReindexSource { - r.scroll = scroll + r.request = r.request.Scroll(scroll) return r } func (r *ReindexSource) Query(query Query) *ReindexSource { - r.query = query + r.request = r.request.Query(query) return r } // Sort adds a sort order. func (r *ReindexSource) Sort(field string, ascending bool) *ReindexSource { - r.sorts = append(r.sorts, SortInfo{Field: field, Ascending: ascending}) + r.request = r.request.Sort(field, ascending) return r } // SortWithInfo adds a sort order. func (r *ReindexSource) SortWithInfo(info SortInfo) *ReindexSource { - r.sorts = append(r.sorts, info) + r.request = r.request.SortWithInfo(info) return r } // SortBy adds a sort order. func (r *ReindexSource) SortBy(sorter ...Sorter) *ReindexSource { - r.sorters = append(r.sorters, sorter...) + r.request = r.request.SortBy(sorter...) + return r +} + +// FetchSource indicates whether the response should contain the stored +// _source for every hit. +func (r *ReindexSource) FetchSource(fetchSource bool) *ReindexSource { + r.request = r.request.FetchSource(fetchSource) + return r +} + +// FetchSourceIncludeExclude specifies that _source should be returned +// with each hit, where "include" and "exclude" serve as a simple wildcard +// matcher that gets applied to its fields +// (e.g. include := []string{"obj1.*","obj2.*"}, exclude := []string{"description.*"}). +func (r *ReindexSource) FetchSourceIncludeExclude(include, exclude []string) *ReindexSource { + r.request = r.request.FetchSourceIncludeExclude(include, exclude) + return r +} + +// FetchSourceContext indicates how the _source should be fetched. +func (r *ReindexSource) FetchSourceContext(fsc *FetchSourceContext) *ReindexSource { + r.request = r.request.FetchSourceContext(fsc) return r } @@ -443,54 +525,28 @@ func (r *ReindexSource) RemoteInfo(ri *ReindexRemoteInfo) *ReindexSource { // Source returns a serializable JSON request for the request. func (r *ReindexSource) Source() (interface{}, error) { - source := make(map[string]interface{}) - - if r.query != nil { - src, err := r.query.Source() - if err != nil { - return nil, err - } - source["query"] = src - } else if r.searchSource != nil { - src, err := r.searchSource.Source() - if err != nil { - return nil, err - } - source["source"] = src + src, err := r.request.sourceAsMap() + if err != nil { + return nil, err } - - if r.searchType != "" { - source["search_type"] = r.searchType + source, ok := src.(map[string]interface{}) + if !ok { + return nil, errors.New("unable to use SearchRequest as map[string]interface{}") } - switch len(r.indices) { - case 0: + switch len(r.request.indices) { case 1: - source["index"] = r.indices[0] + source["index"] = r.request.indices[0] default: - source["index"] = r.indices + source["index"] = r.request.indices } - - switch len(r.types) { + switch len(r.request.types) { case 0: case 1: - source["type"] = r.types[0] + source["type"] = r.request.types[0] default: - source["type"] = r.types - } - - if r.preference != nil && *r.preference != "" { - source["preference"] = *r.preference - } - - if r.requestCache != nil { - source["request_cache"] = fmt.Sprintf("%v", *r.requestCache) - } - - if r.scroll != "" { - source["scroll"] = r.scroll + source["type"] = r.request.types } - if r.remoteInfo != nil { src, err := r.remoteInfo.Source() if err != nil { @@ -498,29 +554,6 @@ func (r *ReindexSource) Source() (interface{}, error) { } source["remote"] = src } - - if len(r.sorters) > 0 { - var sortarr []interface{} - for _, sorter := range r.sorters { - src, err := sorter.Source() - if err != nil { - return nil, err - } - sortarr = append(sortarr, src) - } - source["sort"] = sortarr - } else if len(r.sorts) > 0 { - var sortarr []interface{} - for _, sort := range r.sorts { - src, err := sort.Source() - if err != nil { - return nil, err - } - sortarr = append(sortarr, src) - } - source["sort"] = sortarr - } - return source, nil } @@ -590,13 +623,13 @@ func (ri *ReindexRemoteInfo) Source() (interface{}, error) { return res, nil } -// -source Destination of Reindex -- +// -- Destination of Reindex -- // 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.2/docs-reindex.html -// fsourcer details. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-reindex.html +// for details. type ReindexDestination struct { index string typ string @@ -605,6 +638,7 @@ type ReindexDestination struct { opType string version int64 // default is MATCH_ANY versionType string // default is "internal" + pipeline string } // NewReindexDestination returns a new ReindexDestination. @@ -654,7 +688,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.2/docs-index_.html#operation-type +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-index_.html#operation-type // for details. func (r *ReindexDestination) OpType(opType string) *ReindexDestination { r.opType = opType @@ -674,6 +708,12 @@ func (r *ReindexDestination) VersionType(versionType string) *ReindexDestination return r } +// Pipeline specifies the pipeline to use for reindexing. +func (r *ReindexDestination) Pipeline(pipeline string) *ReindexDestination { + r.pipeline = pipeline + return r +} + // Source returns a serializable JSON request for the request. func (r *ReindexDestination) Source() (interface{}, error) { source := make(map[string]interface{}) @@ -698,5 +738,8 @@ func (r *ReindexDestination) Source() (interface{}, error) { if r.versionType != "" { source["version_type"] = r.versionType } + if r.pipeline != "" { + source["pipeline"] = r.pipeline + } return source, nil } diff --git a/vendor/gopkg.in/olivere/elastic.v6/request.go b/vendor/github.com/olivere/elastic/v7/request.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/request.go rename to vendor/github.com/olivere/elastic/v7/request.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/rescore.go b/vendor/github.com/olivere/elastic/v7/rescore.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/rescore.go rename to vendor/github.com/olivere/elastic/v7/rescore.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/rescorer.go b/vendor/github.com/olivere/elastic/v7/rescorer.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/rescorer.go rename to vendor/github.com/olivere/elastic/v7/rescorer.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/response.go b/vendor/github.com/olivere/elastic/v7/response.go similarity index 52% rename from vendor/gopkg.in/olivere/elastic.v6/response.go rename to vendor/github.com/olivere/elastic/v7/response.go index 4fcdc32..200ed3d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/response.go +++ b/vendor/github.com/olivere/elastic/v7/response.go @@ -6,10 +6,17 @@ package elastic import ( "encoding/json" + "errors" + "io" "io/ioutil" "net/http" ) +var ( + // ErrResponseSize is raised if a response body exceeds the given max body size. + ErrResponseSize = errors.New("elastic: response size too large") +) + // Response represents a response from Elasticsearch. type Response struct { // StatusCode is the HTTP status code, e.g. 200. @@ -19,19 +26,33 @@ type Response struct { Header http.Header // Body is the deserialized response body. Body json.RawMessage + // DeprecationWarnings lists all deprecation warnings returned from + // Elasticsearch. + DeprecationWarnings []string } // newResponse creates a new response from the HTTP response. -func (c *Client) newResponse(res *http.Response) (*Response, error) { +func (c *Client) newResponse(res *http.Response, maxBodySize int64) (*Response, error) { r := &Response{ - StatusCode: res.StatusCode, - Header: res.Header, + StatusCode: res.StatusCode, + Header: res.Header, + DeprecationWarnings: res.Header["Warning"], } if res.Body != nil { - slurp, err := ioutil.ReadAll(res.Body) + body := io.Reader(res.Body) + if maxBodySize > 0 { + if res.ContentLength > maxBodySize { + return nil, ErrResponseSize + } + body = io.LimitReader(body, maxBodySize+1) + } + slurp, err := ioutil.ReadAll(body) if err != nil { return nil, err } + if maxBodySize > 0 && int64(len(slurp)) > maxBodySize { + return nil, ErrResponseSize + } // HEAD requests return a body but no content if len(slurp) > 0 { r.Body = json.RawMessage(slurp) diff --git a/vendor/gopkg.in/olivere/elastic.v6/retrier.go b/vendor/github.com/olivere/elastic/v7/retrier.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/retrier.go rename to vendor/github.com/olivere/elastic/v7/retrier.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/retry.go b/vendor/github.com/olivere/elastic/v7/retry.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/retry.go rename to vendor/github.com/olivere/elastic/v7/retry.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/run-es.sh b/vendor/github.com/olivere/elastic/v7/run-es.sh old mode 100755 new mode 100644 similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/run-es.sh rename to vendor/github.com/olivere/elastic/v7/run-es.sh index 887c1d1..8b60fbc --- a/vendor/gopkg.in/olivere/elastic.v6/run-es.sh +++ b/vendor/github.com/olivere/elastic/v7/run-es.sh @@ -1,3 +1,3 @@ #!/bin/sh -VERSION=${VERSION:=6.3.2} +VERSION=${VERSION:=6.4.0} 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_ diff --git a/vendor/github.com/olivere/elastic/v7/run-tests.sh b/vendor/github.com/olivere/elastic/v7/run-tests.sh new file mode 100644 index 0000000..1204ad3 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/run-tests.sh @@ -0,0 +1,2 @@ +#!/bin/sh +go test . ./aws/... ./config/... ./trace/... ./uritemplates/... diff --git a/vendor/gopkg.in/olivere/elastic.v6/script.go b/vendor/github.com/olivere/elastic/v7/script.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/script.go rename to vendor/github.com/olivere/elastic/v7/script.go index 192c3c3..ce3bd83 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/script.go +++ b/vendor/github.com/olivere/elastic/v7/script.go @@ -4,12 +4,17 @@ package elastic -import "errors" - -// Script holds all the paramaters necessary to compile or find in cache +import ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +// Script holds all the parameters necessary to compile or find in cache // and then execute a script. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details of scripting. type Script struct { script string @@ -53,10 +58,9 @@ func (s *Script) Type(typ string) *Script { return s } -// 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.2/modules-scripting.html +// Lang sets the language of the script. The default scripting language +// is Painless ("painless"). +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details. func (s *Script) Lang(lang string) *Script { s.lang = lang @@ -86,7 +90,11 @@ func (s *Script) Source() (interface{}, error) { source := make(map[string]interface{}) // Beginning with 6.0, the type can only be "source" or "id" if s.typ == "" || s.typ == "inline" { - source["source"] = s.script + src, err := s.rawScriptSource(s.script) + if err != nil { + return nil, err + } + source["source"] = src } else { source["id"] = s.script } @@ -99,13 +107,27 @@ func (s *Script) Source() (interface{}, error) { return source, nil } +// rawScriptSource returns an embeddable script. If it uses a short +// script form, e.g. "ctx._source.likes++" (without the quotes), it +// is quoted. Otherwise it returns the raw script that will be directly +// embedded into the JSON data. +func (s *Script) rawScriptSource(script string) (interface{}, error) { + v := strings.TrimSpace(script) + if !strings.HasPrefix(v, "{") && !strings.HasPrefix(v, `"`) { + v = fmt.Sprintf("%q", v) + } + raw := json.RawMessage(v) + return &raw, nil +} + // -- Script Field -- // ScriptField is a single script field. type ScriptField struct { FieldName string // name of the field - script *Script + script *Script + ignoreFailure *bool // used in e.g. ScriptSource } // NewScriptField creates and initializes a new ScriptField. @@ -113,6 +135,13 @@ func NewScriptField(fieldName string, script *Script) *ScriptField { return &ScriptField{FieldName: fieldName, script: script} } +// IgnoreFailure indicates whether to ignore failures. It is used +// in e.g. ScriptSource. +func (f *ScriptField) IgnoreFailure(ignore bool) *ScriptField { + f.ignoreFailure = &ignore + return f +} + // Source returns the serializable JSON for the ScriptField. func (f *ScriptField) Source() (interface{}, error) { if f.script == nil { @@ -124,5 +153,8 @@ func (f *ScriptField) Source() (interface{}, error) { return nil, err } source["script"] = src + if v := f.ignoreFailure; v != nil { + source["ignore_failure"] = *v + } return source, nil } diff --git a/vendor/gopkg.in/olivere/elastic.v6/script_delete.go b/vendor/github.com/olivere/elastic/v7/script_delete.go similarity index 57% rename from vendor/gopkg.in/olivere/elastic.v6/script_delete.go rename to vendor/github.com/olivere/elastic/v7/script_delete.go index f71b31d..dc68336 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/script_delete.go +++ b/vendor/github.com/olivere/elastic/v7/script_delete.go @@ -7,18 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // DeleteScriptService removes a stored script in Elasticsearch. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details. type DeleteScriptService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string timeout string masterTimeout string @@ -31,6 +39,46 @@ func NewDeleteScriptService(client *Client) *DeleteScriptService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *DeleteScriptService) Pretty(pretty bool) *DeleteScriptService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *DeleteScriptService) Human(human bool) *DeleteScriptService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *DeleteScriptService) ErrorTrace(errorTrace bool) *DeleteScriptService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *DeleteScriptService) FilterPath(filterPath ...string) *DeleteScriptService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *DeleteScriptService) Header(name string, value string) *DeleteScriptService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *DeleteScriptService) Headers(headers http.Header) *DeleteScriptService { + s.headers = headers + return s +} + // Id is the script ID. func (s *DeleteScriptService) Id(id string) *DeleteScriptService { s.id = id @@ -49,12 +97,6 @@ func (s *DeleteScriptService) MasterTimeout(masterTimeout string) *DeleteScriptS return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *DeleteScriptService) Pretty(pretty bool) *DeleteScriptService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *DeleteScriptService) buildURL() (string, string, url.Values, error) { var ( @@ -72,8 +114,17 @@ func (s *DeleteScriptService) buildURL() (string, string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.timeout != "" { params.Set("timeout", s.timeout) @@ -111,9 +162,10 @@ func (s *DeleteScriptService) Do(ctx context.Context) (*DeleteScriptResponse, er // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: method, - Path: path, - Params: params, + Method: method, + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/script_get.go b/vendor/github.com/olivere/elastic/v7/script_get.go similarity index 52% rename from vendor/gopkg.in/olivere/elastic.v6/script_get.go rename to vendor/github.com/olivere/elastic/v7/script_get.go index 313d539..81cedac 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/script_get.go +++ b/vendor/github.com/olivere/elastic/v7/script_get.go @@ -8,19 +8,27 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // GetScriptService reads a stored script in Elasticsearch. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details. type GetScriptService struct { client *Client - pretty bool - id string + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + id string } // NewGetScriptService creates a new GetScriptService. @@ -30,15 +38,49 @@ func NewGetScriptService(client *Client) *GetScriptService { } } -// Id is the script ID. -func (s *GetScriptService) Id(id string) *GetScriptService { - s.id = id +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *GetScriptService) Pretty(pretty bool) *GetScriptService { + s.pretty = &pretty return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *GetScriptService) Pretty(pretty bool) *GetScriptService { - s.pretty = pretty +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *GetScriptService) Human(human bool) *GetScriptService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *GetScriptService) ErrorTrace(errorTrace bool) *GetScriptService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *GetScriptService) FilterPath(filterPath ...string) *GetScriptService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *GetScriptService) Header(name string, value string) *GetScriptService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *GetScriptService) Headers(headers http.Header) *GetScriptService { + s.headers = headers + return s +} + +// Id is the script ID. +func (s *GetScriptService) Id(id string) *GetScriptService { + s.id = id return s } @@ -59,8 +101,17 @@ func (s *GetScriptService) buildURL() (string, string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } return method, path, params, nil } @@ -92,9 +143,10 @@ func (s *GetScriptService) Do(ctx context.Context) (*GetScriptResponse, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: method, - Path: path, - Params: params, + Method: method, + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -108,7 +160,7 @@ func (s *GetScriptService) Do(ctx context.Context) (*GetScriptResponse, error) { return ret, nil } -// GetScriptResponse is the result of deleting a stored script +// GetScriptResponse is the result of getting a stored script // in Elasticsearch. type GetScriptResponse struct { Id string `json:"_id"` diff --git a/vendor/gopkg.in/olivere/elastic.v6/script_put.go b/vendor/github.com/olivere/elastic/v7/script_put.go similarity index 64% rename from vendor/gopkg.in/olivere/elastic.v6/script_put.go rename to vendor/github.com/olivere/elastic/v7/script_put.go index c7310f5..f8b831a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/script_put.go +++ b/vendor/github.com/olivere/elastic/v7/script_put.go @@ -7,18 +7,26 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // PutScriptService adds or updates a stored script in Elasticsearch. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html // for details. type PutScriptService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string context string timeout string @@ -34,6 +42,46 @@ func NewPutScriptService(client *Client) *PutScriptService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *PutScriptService) Pretty(pretty bool) *PutScriptService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *PutScriptService) Human(human bool) *PutScriptService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *PutScriptService) ErrorTrace(errorTrace bool) *PutScriptService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *PutScriptService) FilterPath(filterPath ...string) *PutScriptService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *PutScriptService) Header(name string, value string) *PutScriptService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *PutScriptService) Headers(headers http.Header) *PutScriptService { + s.headers = headers + return s +} + // Id is the script ID. func (s *PutScriptService) Id(id string) *PutScriptService { s.id = id @@ -58,12 +106,6 @@ func (s *PutScriptService) MasterTimeout(masterTimeout string) *PutScriptService return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *PutScriptService) Pretty(pretty bool) *PutScriptService { - s.pretty = pretty - return s -} - // BodyJson is the document as a serializable JSON interface. func (s *PutScriptService) BodyJson(body interface{}) *PutScriptService { s.bodyJson = body @@ -100,8 +142,17 @@ func (s *PutScriptService) buildURL() (string, string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.timeout != "" { params.Set("timeout", s.timeout) @@ -150,10 +201,11 @@ func (s *PutScriptService) Do(ctx context.Context) (*PutScriptResponse, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: method, - Path: path, - Params: params, - Body: body, + Method: method, + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/scroll.go b/vendor/github.com/olivere/elastic/v7/scroll.go similarity index 67% rename from vendor/gopkg.in/olivere/elastic.v6/scroll.go rename to vendor/github.com/olivere/elastic/v7/scroll.go index 7a2671c..3819d91 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/scroll.go +++ b/vendor/github.com/olivere/elastic/v7/scroll.go @@ -8,11 +8,12 @@ import ( "context" "fmt" "io" + "net/http" "net/url" "strings" "sync" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) const ( @@ -22,20 +23,27 @@ const ( // ScrollService iterates over pages of search results from Elasticsearch. type ScrollService struct { - client *Client - retrier Retrier + client *Client + retrier Retrier + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + indices []string types []string keepAlive string body interface{} ss *SearchSource size *int - pretty bool routing string preference string ignoreUnavailable *bool allowNoIndices *bool expandWildcards string + maxResponseSize int64 mu sync.RWMutex scrollId string @@ -51,6 +59,46 @@ func NewScrollService(client *Client) *ScrollService { return builder } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ScrollService) Pretty(pretty bool) *ScrollService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ScrollService) Human(human bool) *ScrollService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ScrollService) ErrorTrace(errorTrace bool) *ScrollService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ScrollService) FilterPath(filterPath ...string) *ScrollService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ScrollService) Header(name string, value string) *ScrollService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ScrollService) Headers(headers http.Header) *ScrollService { + s.headers = headers + return s +} + // Retrier allows to set specific retry logic for this ScrollService. // If not specified, it will use the client's default retrier. func (s *ScrollService) Retrier(retrier Retrier) *ScrollService { @@ -68,6 +116,9 @@ func (s *ScrollService) Index(indices ...string) *ScrollService { } // Type sets the name of one or more types to iterate over. +// +// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to +// filter on a field on the document. func (s *ScrollService) Type(types ...string) *ScrollService { if s.types == nil { s.types = make([]string, 0) @@ -84,7 +135,7 @@ func (s *ScrollService) Scroll(keepAlive string) *ScrollService { } // KeepAlive sets the maximum time after which the cursor will expire. -// It is "2m" by default. +// It is "5m" by default. func (s *ScrollService) KeepAlive(keepAlive string) *ScrollService { s.keepAlive = keepAlive return s @@ -97,6 +148,12 @@ func (s *ScrollService) Size(size int) *ScrollService { return s } +// Highlight allows to highlight search results on one or more fields +func (s *ScrollService) Highlight(highlight *Highlight) *ScrollService { + s.ss = s.ss.Highlight(highlight) + return s +} + // 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 @@ -125,7 +182,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.2/search-request-post-filter.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-post-filter.html // for details. func (s *ScrollService) PostFilter(postFilter Query) *ScrollService { s.ss = s.ss.PostFilter(postFilter) @@ -134,7 +191,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.2/search-request-scroll.html#sliced-scroll +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-scroll.html#sliced-scroll // for details. func (s *ScrollService) Slice(sliceQuery Query) *ScrollService { s.ss = s.ss.Slice(sliceQuery) @@ -155,7 +212,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.2/search-request-version.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-version.html. func (s *ScrollService) Version(version bool) *ScrollService { s.ss = s.ss.Version(version) return s @@ -182,9 +239,12 @@ func (s *ScrollService) SortBy(sorter ...Sorter) *ScrollService { return s } -// Pretty asks Elasticsearch to pretty-print the returned JSON. -func (s *ScrollService) Pretty(pretty bool) *ScrollService { - s.pretty = pretty +// TrackTotalHits controls if the total hit count for the query should be tracked. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-track-total-hits.html +// for details. +func (s *ScrollService) TrackTotalHits(trackTotalHits interface{}) *ScrollService { + s.ss = s.ss.TrackTotalHits(trackTotalHits) return s } @@ -227,6 +287,13 @@ func (s *ScrollService) ExpandWildcards(expandWildcards string) *ScrollService { return s } +// MaxResponseSize sets an upper limit on the response body size that we accept, +// to guard against OOM situations. +func (s *ScrollService) MaxResponseSize(maxResponseSize int64) *ScrollService { + s.maxResponseSize = maxResponseSize + return s +} + // ScrollId specifies the identifier of a scroll in action. func (s *ScrollService) ScrollId(scrollId string) *ScrollService { s.mu.Lock() @@ -260,6 +327,18 @@ func (s *ScrollService) Clear(ctx context.Context) error { path := "/_search/scroll" params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } body := struct { ScrollId []string `json:"scroll_id,omitempty"` }{ @@ -298,11 +377,13 @@ func (s *ScrollService) first(ctx context.Context) (*SearchResult, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, - Retrier: s.retrier, + Method: "POST", + Path: path, + Params: params, + Body: body, + Retrier: s.retrier, + Headers: s.headers, + MaxResponseSize: s.maxResponseSize, }) if err != nil { return nil, err @@ -317,7 +398,7 @@ func (s *ScrollService) first(ctx context.Context) (*SearchResult, error) { s.scrollId = ret.ScrollId s.mu.Unlock() if ret.Hits == nil || len(ret.Hits.Hits) == 0 { - return nil, io.EOF + return ret, io.EOF } return ret, nil } @@ -349,8 +430,28 @@ func (s *ScrollService) buildFirstURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + // Always add "hits._scroll_id", otherwise we cannot scroll + var found bool + for _, path := range s.filterPath { + if path == "_scroll_id" { + found = true + break + } + } + if !found { + s.filterPath = append(s.filterPath, "_scroll_id") + } + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.size != nil && *s.size > 0 { params.Set("size", fmt.Sprintf("%d", *s.size)) @@ -418,11 +519,13 @@ func (s *ScrollService) next(ctx context.Context) (*SearchResult, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, - Retrier: s.retrier, + Method: "POST", + Path: path, + Params: params, + Body: body, + Retrier: s.retrier, + Headers: s.headers, + MaxResponseSize: s.maxResponseSize, }) if err != nil { return nil, err @@ -437,7 +540,7 @@ func (s *ScrollService) next(ctx context.Context) (*SearchResult, error) { s.scrollId = ret.ScrollId s.mu.Unlock() if ret.Hits == nil || len(ret.Hits.Hits) == 0 { - return nil, io.EOF + return ret, io.EOF } return ret, nil } @@ -448,8 +551,28 @@ func (s *ScrollService) buildNextURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + // Always add "hits._scroll_id", otherwise we cannot scroll + var found bool + for _, path := range s.filterPath { + if path == "_scroll_id" { + found = true + break + } + } + if !found { + s.filterPath = append(s.filterPath, "_scroll_id") + } + params.Set("filter_path", strings.Join(s.filterPath, ",")) } return path, params, nil @@ -468,3 +591,31 @@ func (s *ScrollService) bodyNext() (interface{}, error) { s.mu.RUnlock() return body, nil } + +// DocvalueField adds a single field to load from the field data cache +// and return as part of the search. +func (s *ScrollService) DocvalueField(docvalueField string) *ScrollService { + s.ss = s.ss.DocvalueField(docvalueField) + return s +} + +// DocvalueFieldWithFormat adds a single field to load from the field data cache +// and return as part of the search. +func (s *ScrollService) DocvalueFieldWithFormat(docvalueField DocvalueField) *ScrollService { + s.ss = s.ss.DocvalueFieldWithFormat(docvalueField) + return s +} + +// DocvalueFields adds one or more fields to load from the field data cache +// and return as part of the search. +func (s *ScrollService) DocvalueFields(docvalueFields ...string) *ScrollService { + s.ss = s.ss.DocvalueFields(docvalueFields...) + return s +} + +// DocvalueFieldsWithFormat adds one or more fields to load from the field data cache +// and return as part of the search. +func (s *ScrollService) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *ScrollService { + s.ss = s.ss.DocvalueFieldsWithFormat(docvalueFields...) + return s +} diff --git a/vendor/github.com/olivere/elastic/v7/search.go b/vendor/github.com/olivere/elastic/v7/search.go new file mode 100644 index 0000000..1635104 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search.go @@ -0,0 +1,868 @@ +// 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/http" + "net/url" + "reflect" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// Search for documents in Elasticsearch. +type SearchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + searchSource *SearchSource // q + source interface{} + searchType string // search_type + index []string + typ []string + routing string // routing + preference string // preference + requestCache *bool // request_cache + ignoreUnavailable *bool // ignore_unavailable + ignoreThrottled *bool // ignore_throttled + allowNoIndices *bool // allow_no_indices + expandWildcards string // expand_wildcards + lenient *bool // lenient + maxResponseSize int64 + allowPartialSearchResults *bool // allow_partial_search_results + typedKeys *bool // typed_keys + seqNoPrimaryTerm *bool // seq_no_primary_term + batchedReduceSize *int // batched_reduce_size + maxConcurrentShardRequests *int // max_concurrent_shard_requests + preFilterShardSize *int // pre_filter_shard_size + restTotalHitsAsInt *bool // rest_total_hits_as_int + + ccsMinimizeRoundtrips *bool // ccs_minimize_roundtrips + +} + +// NewSearchService creates a new service for searching in Elasticsearch. +func NewSearchService(client *Client) *SearchService { + builder := &SearchService{ + client: client, + searchSource: NewSearchSource(), + } + return builder +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SearchService) Pretty(pretty bool) *SearchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SearchService) Human(human bool) *SearchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SearchService) ErrorTrace(errorTrace bool) *SearchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SearchService) FilterPath(filterPath ...string) *SearchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SearchService) Header(name string, value string) *SearchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SearchService) Headers(headers http.Header) *SearchService { + s.headers = headers + return s +} + +// SearchSource sets the search source builder to use with this service. +func (s *SearchService) SearchSource(searchSource *SearchSource) *SearchService { + s.searchSource = searchSource + if s.searchSource == nil { + s.searchSource = NewSearchSource() + } + return s +} + +// Source allows the user to set the request body manually without using +// any of the structs and interfaces in Elastic. +func (s *SearchService) Source(source interface{}) *SearchService { + s.source = source + return s +} + +// Index sets the names of the indices to use for search. +func (s *SearchService) Index(index ...string) *SearchService { + s.index = append(s.index, index...) + return s +} + +// Type adds search restrictions for a list of types. +// +// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to +// filter on a field on the document. +func (s *SearchService) Type(typ ...string) *SearchService { + s.typ = append(s.typ, typ...) + return s +} + +// Timeout sets the timeout to use, e.g. "1s" or "1000ms". +func (s *SearchService) Timeout(timeout string) *SearchService { + s.searchSource = s.searchSource.Timeout(timeout) + return s +} + +// Profile sets the Profile API flag on the search source. +// When enabled, a search executed by this service will return query +// profiling data. +func (s *SearchService) Profile(profile bool) *SearchService { + s.searchSource = s.searchSource.Profile(profile) + return s +} + +// Collapse adds field collapsing. +func (s *SearchService) Collapse(collapse *CollapseBuilder) *SearchService { + s.searchSource = s.searchSource.Collapse(collapse) + return s +} + +// TimeoutInMillis sets the timeout in milliseconds. +func (s *SearchService) TimeoutInMillis(timeoutInMillis int) *SearchService { + s.searchSource = s.searchSource.TimeoutInMillis(timeoutInMillis) + 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: +// "dfs_query_then_fetch" and "query_then_fetch". +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-search-type.html +// for details. +func (s *SearchService) SearchType(searchType string) *SearchService { + s.searchType = searchType + return s +} + +// Routing is a list of specific routing values to control the shards +// the search will be executed on. +func (s *SearchService) Routing(routings ...string) *SearchService { + s.routing = strings.Join(routings, ",") + return s +} + +// Preference sets the preference to execute the search. Defaults to +// randomize across shards ("random"). Can be set to "_local" to prefer +// local shards, "_primary" to execute on primary shards only, +// or a custom value which guarantees that the same order will be used +// across different requests. +func (s *SearchService) Preference(preference string) *SearchService { + s.preference = preference + return s +} + +// RequestCache indicates whether the cache should be used for this +// request or not, defaults to index level setting. +func (s *SearchService) RequestCache(requestCache bool) *SearchService { + s.requestCache = &requestCache + return s +} + +// Query sets the query to perform, e.g. MatchAllQuery. +func (s *SearchService) Query(query Query) *SearchService { + s.searchSource = s.searchSource.Query(query) + return s +} + +// PostFilter will be executed after the query has been executed and +// only affects the search hits, not the aggregations. +// This filter is always executed as the last filtering mechanism. +func (s *SearchService) PostFilter(postFilter Query) *SearchService { + s.searchSource = s.searchSource.PostFilter(postFilter) + return s +} + +// FetchSource indicates whether the response should contain the stored +// _source for every hit. +func (s *SearchService) FetchSource(fetchSource bool) *SearchService { + s.searchSource = s.searchSource.FetchSource(fetchSource) + return s +} + +// FetchSourceContext indicates how the _source should be fetched. +func (s *SearchService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *SearchService { + s.searchSource = s.searchSource.FetchSourceContext(fetchSourceContext) + return s +} + +// Highlight adds highlighting to the search. +func (s *SearchService) Highlight(highlight *Highlight) *SearchService { + s.searchSource = s.searchSource.Highlight(highlight) + return s +} + +// GlobalSuggestText defines the global text to use with all suggesters. +// This avoids repetition. +func (s *SearchService) GlobalSuggestText(globalText string) *SearchService { + s.searchSource = s.searchSource.GlobalSuggestText(globalText) + return s +} + +// Suggester adds a suggester to the search. +func (s *SearchService) Suggester(suggester Suggester) *SearchService { + s.searchSource = s.searchSource.Suggester(suggester) + return s +} + +// Aggregation adds an aggreation to perform as part of the search. +func (s *SearchService) Aggregation(name string, aggregation Aggregation) *SearchService { + s.searchSource = s.searchSource.Aggregation(name, aggregation) + return s +} + +// MinScore sets the minimum score below which docs will be filtered out. +func (s *SearchService) MinScore(minScore float64) *SearchService { + s.searchSource = s.searchSource.MinScore(minScore) + return s +} + +// From index to start the search from. Defaults to 0. +func (s *SearchService) From(from int) *SearchService { + s.searchSource = s.searchSource.From(from) + return s +} + +// Size is the number of search hits to return. Defaults to 10. +func (s *SearchService) Size(size int) *SearchService { + s.searchSource = s.searchSource.Size(size) + return s +} + +// Explain indicates whether each search hit should be returned with +// an explanation of the hit (ranking). +func (s *SearchService) Explain(explain bool) *SearchService { + s.searchSource = s.searchSource.Explain(explain) + return s +} + +// Version indicates whether each search hit should be returned with +// a version associated to it. +func (s *SearchService) Version(version bool) *SearchService { + s.searchSource = s.searchSource.Version(version) + return s +} + +// Sort adds a sort order. +func (s *SearchService) Sort(field string, ascending bool) *SearchService { + s.searchSource = s.searchSource.Sort(field, ascending) + return s +} + +// SortWithInfo adds a sort order. +func (s *SearchService) SortWithInfo(info SortInfo) *SearchService { + s.searchSource = s.searchSource.SortWithInfo(info) + return s +} + +// SortBy adds a sort order. +func (s *SearchService) SortBy(sorter ...Sorter) *SearchService { + s.searchSource = s.searchSource.SortBy(sorter...) + return s +} + +// DocvalueField adds a single field to load from the field data cache +// and return as part of the search. +func (s *SearchService) DocvalueField(docvalueField string) *SearchService { + s.searchSource = s.searchSource.DocvalueField(docvalueField) + return s +} + +// DocvalueFieldWithFormat adds a single field to load from the field data cache +// and return as part of the search. +func (s *SearchService) DocvalueFieldWithFormat(docvalueField DocvalueField) *SearchService { + s.searchSource = s.searchSource.DocvalueFieldWithFormat(docvalueField) + return s +} + +// DocvalueFields adds one or more fields to load from the field data cache +// and return as part of the search. +func (s *SearchService) DocvalueFields(docvalueFields ...string) *SearchService { + s.searchSource = s.searchSource.DocvalueFields(docvalueFields...) + return s +} + +// DocvalueFieldsWithFormat adds one or more fields to load from the field data cache +// and return as part of the search. +func (s *SearchService) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *SearchService { + s.searchSource = s.searchSource.DocvalueFieldsWithFormat(docvalueFields...) + return s +} + +// NoStoredFields indicates that no stored fields should be loaded, resulting in only +// id and type to be returned per field. +func (s *SearchService) NoStoredFields() *SearchService { + s.searchSource = s.searchSource.NoStoredFields() + return s +} + +// StoredField adds a single field to load and return (note, must be stored) as +// part of the search request. If none are specified, the source of the +// document will be returned. +func (s *SearchService) StoredField(fieldName string) *SearchService { + s.searchSource = s.searchSource.StoredField(fieldName) + return s +} + +// StoredFields sets the fields to load and return as part of the search request. +// If none are specified, the source of the document will be returned. +func (s *SearchService) StoredFields(fields ...string) *SearchService { + s.searchSource = s.searchSource.StoredFields(fields...) + return s +} + +// TrackScores is applied when sorting and controls if scores will be +// tracked as well. Defaults to false. +func (s *SearchService) TrackScores(trackScores bool) *SearchService { + s.searchSource = s.searchSource.TrackScores(trackScores) + return s +} + +// TrackTotalHits controls if the total hit count for the query should be tracked. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-track-total-hits.html +// for details. +func (s *SearchService) TrackTotalHits(trackTotalHits interface{}) *SearchService { + s.searchSource = s.searchSource.TrackTotalHits(trackTotalHits) + return s +} + +// 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/7.0/search-request-search-after.html +func (s *SearchService) SearchAfter(sortValues ...interface{}) *SearchService { + s.searchSource = s.searchSource.SearchAfter(sortValues...) + return s +} + +// DefaultRescoreWindowSize sets the rescore window size for rescores +// that don't specify their window. +func (s *SearchService) DefaultRescoreWindowSize(defaultRescoreWindowSize int) *SearchService { + s.searchSource = s.searchSource.DefaultRescoreWindowSize(defaultRescoreWindowSize) + return s +} + +// Rescorer adds a rescorer to the search. +func (s *SearchService) Rescorer(rescore *Rescore) *SearchService { + s.searchSource = s.searchSource.Rescorer(rescore) + return s +} + +// IgnoreUnavailable indicates whether the specified concrete indices +// should be ignored when unavailable (missing or closed). +func (s *SearchService) IgnoreUnavailable(ignoreUnavailable bool) *SearchService { + s.ignoreUnavailable = &ignoreUnavailable + return s +} + +// IgnoreThrottled indicates whether specified concrete, expanded or aliased +// indices should be ignored when throttled. +func (s *SearchService) IgnoreThrottled(ignoreThrottled bool) *SearchService { + s.ignoreThrottled = &ignoreThrottled + 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 *SearchService) AllowNoIndices(allowNoIndices bool) *SearchService { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards indicates whether to expand wildcard expression to +// concrete indices that are open, closed or both. +func (s *SearchService) ExpandWildcards(expandWildcards string) *SearchService { + s.expandWildcards = expandWildcards + return s +} + +// Lenient specifies whether format-based query failures (such as providing +// text to a numeric field) should be ignored. +func (s *SearchService) Lenient(lenient bool) *SearchService { + s.lenient = &lenient + return s +} + +// MaxResponseSize sets an upper limit on the response body size that we accept, +// to guard against OOM situations. +func (s *SearchService) MaxResponseSize(maxResponseSize int64) *SearchService { + s.maxResponseSize = maxResponseSize + return s +} + +// AllowPartialSearchResults indicates if an error should be returned if +// there is a partial search failure or timeout. +func (s *SearchService) AllowPartialSearchResults(enabled bool) *SearchService { + s.allowPartialSearchResults = &enabled + return s +} + +// TypedKeys specifies whether aggregation and suggester names should be +// prefixed by their respective types in the response. +func (s *SearchService) TypedKeys(enabled bool) *SearchService { + s.typedKeys = &enabled + return s +} + +// SeqNoPrimaryTerm specifies whether to return sequence number and +// primary term of the last modification of each hit. +func (s *SearchService) SeqNoPrimaryTerm(enabled bool) *SearchService { + s.seqNoPrimaryTerm = &enabled + return s +} + +// BatchedReduceSize specifies the number of shard results that should be reduced +// at once on the coordinating node. This value should be used as a protection +// mechanism to reduce the memory overhead per search request if the potential +// number of shards in the request can be large. +func (s *SearchService) BatchedReduceSize(size int) *SearchService { + s.batchedReduceSize = &size + return s +} + +// MaxConcurrentShardRequests specifies the number of concurrent shard requests +// this search executes concurrently. This value should be used to limit the +// impact of the search on the cluster in order to limit the number of +// concurrent shard requests. +func (s *SearchService) MaxConcurrentShardRequests(max int) *SearchService { + s.maxConcurrentShardRequests = &max + return s +} + +// PreFilterShardSize specifies a threshold that enforces a pre-filter roundtrip +// to prefilter search shards based on query rewriting if the number of shards +// the search request expands to exceeds the threshold. This filter roundtrip +// can limit the number of shards significantly if for instance a shard can +// not match any documents based on it's rewrite method i.e. if date filters are +// mandatory to match but the shard bounds and the query are disjoint. +func (s *SearchService) PreFilterShardSize(threshold int) *SearchService { + s.preFilterShardSize = &threshold + return s +} + +// RestTotalHitsAsInt indicates whether hits.total should be rendered as an +// integer or an object in the rest search response. +func (s *SearchService) RestTotalHitsAsInt(enabled bool) *SearchService { + s.restTotalHitsAsInt = &enabled + return s +} + +// CCSMinimizeRoundtrips indicates whether network round-trips should be minimized +// as part of cross-cluster search requests execution. +func (s *SearchService) CCSMinimizeRoundtrips(enabled bool) *SearchService { + s.ccsMinimizeRoundtrips = &enabled + return s +} + +// buildURL builds the URL for the operation. +func (s *SearchService) buildURL() (string, url.Values, error) { + var err error + var path string + + if len(s.index) > 0 && len(s.typ) > 0 { + path, err = uritemplates.Expand("/{index}/{type}/_search", map[string]string{ + "index": strings.Join(s.index, ","), + "type": strings.Join(s.typ, ","), + }) + } else if len(s.index) > 0 { + path, err = uritemplates.Expand("/{index}/_search", map[string]string{ + "index": strings.Join(s.index, ","), + }) + } else if len(s.typ) > 0 { + path, err = uritemplates.Expand("/_all/{type}/_search", map[string]string{ + "type": strings.Join(s.typ, ","), + }) + } else { + path = "/_search" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.searchType != "" { + params.Set("search_type", s.searchType) + } + if s.routing != "" { + params.Set("routing", s.routing) + } + if s.preference != "" { + params.Set("preference", s.preference) + } + if v := s.requestCache; v != nil { + params.Set("request_cache", fmt.Sprint(*v)) + } + if v := s.allowNoIndices; v != nil { + params.Set("allow_no_indices", fmt.Sprint(*v)) + } + if s.expandWildcards != "" { + params.Set("expand_wildcards", s.expandWildcards) + } + if v := s.lenient; v != nil { + params.Set("lenient", fmt.Sprint(*v)) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) + } + if v := s.ignoreThrottled; v != nil { + params.Set("ignore_throttled", fmt.Sprint(*v)) + } + if s.seqNoPrimaryTerm != nil { + params.Set("seq_no_primary_term", fmt.Sprint(*s.seqNoPrimaryTerm)) + } + if v := s.allowPartialSearchResults; v != nil { + params.Set("allow_partial_search_results", fmt.Sprint(*v)) + } + if v := s.typedKeys; v != nil { + params.Set("typed_keys", fmt.Sprint(*v)) + } + if v := s.batchedReduceSize; v != nil { + params.Set("batched_reduce_size", fmt.Sprint(*v)) + } + if v := s.maxConcurrentShardRequests; v != nil { + params.Set("max_concurrent_shard_requests", fmt.Sprint(*v)) + } + if v := s.preFilterShardSize; v != nil { + params.Set("pre_filter_shard_size", fmt.Sprint(*v)) + } + if v := s.restTotalHitsAsInt; v != nil { + params.Set("rest_total_hits_as_int", fmt.Sprint(*v)) + } + if v := s.ccsMinimizeRoundtrips; v != nil { + params.Set("ccs_minimize_roundtrips", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *SearchService) Validate() error { + return nil +} + +// Do executes the search and returns a SearchResult. +func (s *SearchService) Do(ctx context.Context) (*SearchResult, 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 + } + + // Perform request + var body interface{} + if s.source != nil { + body = s.source + } else { + src, err := s.searchSource.Source() + if err != nil { + return nil, err + } + body = src + } + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + MaxResponseSize: s.maxResponseSize, + }) + if err != nil { + return nil, err + } + + // Return search results + ret := new(SearchResult) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + ret.Header = res.Header + return nil, err + } + ret.Header = res.Header + return ret, nil +} + +// SearchResult is the result of a search in Elasticsearch. +type SearchResult struct { + Header http.Header `json:"-"` + TookInMillis int64 `json:"took,omitempty"` // search time in milliseconds + TerminatedEarly bool `json:"terminated_early,omitempty"` // request terminated early + NumReducePhases int `json:"num_reduce_phases,omitempty"` + Clusters *SearchResultCluster `json:"_clusters,omitempty"` // 6.1.0+ + ScrollId string `json:"_scroll_id,omitempty"` // only used with Scroll and Scan operations + Hits *SearchHits `json:"hits,omitempty"` // the actual search hits + Suggest SearchSuggest `json:"suggest,omitempty"` // results from suggesters + Aggregations Aggregations `json:"aggregations,omitempty"` // results from aggregations + TimedOut bool `json:"timed_out,omitempty"` // true if the search timed out + Error *ErrorDetails `json:"error,omitempty"` // only used in MultiGet + Profile *SearchProfile `json:"profile,omitempty"` // profiling results, if optional Profile API was active for this search + Shards *ShardsInfo `json:"_shards,omitempty"` // shard information + Status int `json:"status,omitempty"` // used in MultiSearch +} + +// SearchResultCluster holds information about a search response +// from a cluster. +type SearchResultCluster struct { + Successful int `json:"successful,omitempty"` + Total int `json:"total,omitempty"` + Skipped int `json:"skipped,omitempty"` +} + +// TotalHits is a convenience function to return the number of hits for +// a search result. The return value might not be accurate, unless +// track_total_hits parameter has set to true. +func (r *SearchResult) TotalHits() int64 { + if r.Hits != nil && r.Hits.TotalHits != nil { + return r.Hits.TotalHits.Value + } + return 0 +} + +// 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 +func (r *SearchResult) Each(typ reflect.Type) []interface{} { + if r.Hits == nil || r.Hits.Hits == nil || len(r.Hits.Hits) == 0 { + return nil + } + var slice []interface{} + for _, hit := range r.Hits.Hits { + v := reflect.New(typ).Elem() + if hit.Source == nil { + slice = append(slice, v.Interface()) + continue + } + if err := json.Unmarshal(hit.Source, v.Addr().Interface()); err == nil { + slice = append(slice, v.Interface()) + } + } + return slice +} + +// SearchHits specifies the list of search hits. +type SearchHits struct { + TotalHits *TotalHits `json:"total,omitempty"` // total number of hits found + MaxScore *float64 `json:"max_score,omitempty"` // maximum score of all hits + Hits []*SearchHit `json:"hits,omitempty"` // the actual hits returned +} + +// NestedHit is a nested innerhit +type NestedHit struct { + Field string `json:"field"` + Offset int `json:"offset,omitempty"` + Child *NestedHit `json:"_nested,omitempty"` +} + +// TotalHits specifies total number of hits and its relation +type TotalHits struct { + Value int64 `json:"value"` // value of the total hit count + Relation string `json:"relation"` // how the value should be interpreted: accurate ("eq") or a lower bound ("gte") +} + +// UnmarshalJSON into TotalHits, accepting both the new response structure +// in ES 7.x as well as the older response structure in earlier versions. +// The latter can be enabled with RestTotalHitsAsInt(true). +func (h *TotalHits) UnmarshalJSON(data []byte) error { + if data == nil || string(data) == "null" { + return nil + } + var v struct { + Value int64 `json:"value"` // value of the total hit count + Relation string `json:"relation"` // how the value should be interpreted: accurate ("eq") or a lower bound ("gte") + } + if err := json.Unmarshal(data, &v); err != nil { + var count int64 + if err2 := json.Unmarshal(data, &count); err2 != nil { + return err // return inner error + } + h.Value = count + h.Relation = "eq" + return nil + } + *h = v + return nil +} + +// SearchHit is a single hit. +type SearchHit struct { + Score *float64 `json:"_score,omitempty"` // computed score + Index string `json:"_index,omitempty"` // index name + Type string `json:"_type,omitempty"` // type meta field + Id string `json:"_id,omitempty"` // external or internal + Uid string `json:"_uid,omitempty"` // uid meta field (see MapperService.java for all meta fields) + Routing string `json:"_routing,omitempty"` // routing meta field + Parent string `json:"_parent,omitempty"` // parent meta field + Version *int64 `json:"_version,omitempty"` // version number, when Version is set to true in SearchService + SeqNo *int64 `json:"_seq_no"` + PrimaryTerm *int64 `json:"_primary_term"` + Sort []interface{} `json:"sort,omitempty"` // sort information + Highlight SearchHitHighlight `json:"highlight,omitempty"` // highlighter information + Source json.RawMessage `json:"_source,omitempty"` // stored document source + Fields map[string]interface{} `json:"fields,omitempty"` // returned (stored) fields + Explanation *SearchExplanation `json:"_explanation,omitempty"` // explains how the score was computed + MatchedQueries []string `json:"matched_queries,omitempty"` // matched queries + InnerHits map[string]*SearchHitInnerHits `json:"inner_hits,omitempty"` // inner hits with ES >= 1.5.0 + Nested *NestedHit `json:"_nested,omitempty"` // for nested inner hits + Shard string `json:"_shard,omitempty"` // used e.g. in Search Explain + Node string `json:"_node,omitempty"` // used e.g. in Search Explain + + // HighlightFields + // SortValues + // MatchedFilters +} + +// SearchHitInnerHits is used for inner hits. +type SearchHitInnerHits struct { + Hits *SearchHits `json:"hits,omitempty"` +} + +// SearchExplanation explains how the score for a hit was computed. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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:" + Details []SearchExplanation `json:"details,omitempty"` // recursive details +} + +// Suggest + +// SearchSuggest is a map of suggestions. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters.html. +type SearchSuggest map[string][]SearchSuggestion + +// SearchSuggestion is a single search suggestion. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters.html. +type SearchSuggestion struct { + Text string `json:"text"` + Offset int `json:"offset"` + Length int `json:"length"` + Options []SearchSuggestionOption `json:"options"` +} + +// SearchSuggestionOption is an option of a SearchSuggestion. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters.html. +type SearchSuggestionOption struct { + Text string `json:"text"` + Index string `json:"_index"` + Type string `json:"_type"` + Id string `json:"_id"` + Score float64 `json:"score"` // term and phrase suggesters uses "score" as of 6.2.4 + ScoreUnderscore float64 `json:"_score"` // completion and context suggesters uses "_score" as of 6.2.4 + Highlighted string `json:"highlighted"` + CollateMatch bool `json:"collate_match"` + Freq int `json:"freq"` // from TermSuggestion.Option in Java API + Source json.RawMessage `json:"_source"` + Contexts map[string][]string `json:"contexts,omitempty"` +} + +// SearchProfile is a list of shard profiling data collected during +// query execution in the "profile" section of a SearchResult +type SearchProfile struct { + Shards []SearchProfileShardResult `json:"shards"` +} + +// SearchProfileShardResult returns the profiling data for a single shard +// accessed during the search query or aggregation. +type SearchProfileShardResult struct { + ID string `json:"id"` + Searches []QueryProfileShardResult `json:"searches"` + Aggregations []ProfileResult `json:"aggregations"` +} + +// QueryProfileShardResult is a container class to hold the profile results +// for a single shard in the request. It comtains a list of query profiles, +// a collector tree and a total rewrite tree. +type QueryProfileShardResult struct { + Query []ProfileResult `json:"query,omitempty"` + RewriteTime int64 `json:"rewrite_time,omitempty"` + Collector []interface{} `json:"collector,omitempty"` +} + +// CollectorResult holds the profile timings of the collectors used in the +// search. Children's CollectorResults may be embedded inside of a parent +// CollectorResult. +type CollectorResult struct { + Name string `json:"name,omitempty"` + Reason string `json:"reason,omitempty"` + Time string `json:"time,omitempty"` + TimeNanos int64 `json:"time_in_nanos,omitempty"` + Children []CollectorResult `json:"children,omitempty"` +} + +// ProfileResult is the internal representation of a profiled query, +// corresponding to a single node in the query tree. +type ProfileResult struct { + Type string `json:"type"` + Description string `json:"description,omitempty"` + NodeTime string `json:"time,omitempty"` + NodeTimeNanos int64 `json:"time_in_nanos,omitempty"` + Breakdown map[string]int64 `json:"breakdown,omitempty"` + Children []ProfileResult `json:"children,omitempty"` +} + +// Aggregations (see search_aggs.go) + +// Highlighting + +// SearchHitHighlight is the highlight information of a search hit. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-highlighting.html +// for a general discussion of highlighting. +type SearchHitHighlight map[string][]string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs.go b/vendor/github.com/olivere/elastic/v7/search_aggs.go similarity index 71% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs.go rename to vendor/github.com/olivere/elastic/v7/search_aggs.go index 62bbd08..0ba9ebf 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations.html type Aggregation interface { // Source returns a JSON-serializable aggregation that is a fragment // of the request sent to Elasticsearch. @@ -21,17 +21,17 @@ type Aggregation interface { } // Aggregations is a list of aggregations that are part of a search result. -type Aggregations map[string]*json.RawMessage +type Aggregations map[string]json.RawMessage // Min returns min aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-min-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-min-aggregation.html func (a Aggregations) Min(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -39,14 +39,14 @@ func (a Aggregations) Min(name string) (*AggregationValueMetric, bool) { } // Max returns max aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-max-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-max-aggregation.html func (a Aggregations) Max(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -54,14 +54,14 @@ func (a Aggregations) Max(name string) (*AggregationValueMetric, bool) { } // Sum returns sum aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-sum-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-sum-aggregation.html func (a Aggregations) Sum(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -69,14 +69,45 @@ func (a Aggregations) Sum(name string) (*AggregationValueMetric, bool) { } // Avg returns average aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-avg-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-avg-aggregation.html func (a Aggregations) Avg(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// WeightedAvg computes the weighted average of numeric values that are extracted from the aggregated documents. +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-weight-avg-aggregation.html +func (a Aggregations) WeightedAvg(name string) (*AggregationValueMetric, bool) { + if raw, found := a[name]; found { + agg := new(AggregationValueMetric) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// MedianAbsoluteDeviation returns median absolute deviation aggregation results. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.6/search-aggregations-metrics-median-absolute-deviation-aggregation.html +// for details. +func (a Aggregations) MedianAbsoluteDeviation(name string) (*AggregationValueMetric, bool) { + if raw, found := a[name]; found { + agg := new(AggregationValueMetric) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -84,14 +115,14 @@ func (a Aggregations) Avg(name string) (*AggregationValueMetric, bool) { } // ValueCount returns value-count aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-valuecount-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-valuecount-aggregation.html func (a Aggregations) ValueCount(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -99,14 +130,14 @@ func (a Aggregations) ValueCount(name string) (*AggregationValueMetric, bool) { } // Cardinality returns cardinality aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-cardinality-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-cardinality-aggregation.html func (a Aggregations) Cardinality(name string) (*AggregationValueMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationValueMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -114,14 +145,14 @@ func (a Aggregations) Cardinality(name string) (*AggregationValueMetric, bool) { } // Stats returns stats aggregation results. -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-stats-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-stats-aggregation.html func (a Aggregations) Stats(name string) (*AggregationStatsMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationStatsMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -129,14 +160,14 @@ func (a Aggregations) Stats(name string) (*AggregationStatsMetric, bool) { } // ExtendedStats returns extended stats aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-extendedstats-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-extendedstats-aggregation.html func (a Aggregations) ExtendedStats(name string) (*AggregationExtendedStatsMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationExtendedStatsMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -144,14 +175,14 @@ func (a Aggregations) ExtendedStats(name string) (*AggregationExtendedStatsMetri } // MatrixStats returns matrix stats aggregation results. -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-matrix-stats-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-matrix-stats-aggregation.html func (a Aggregations) MatrixStats(name string) (*AggregationMatrixStats, bool) { if raw, found := a[name]; found { agg := new(AggregationMatrixStats) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -159,14 +190,14 @@ func (a Aggregations) MatrixStats(name string) (*AggregationMatrixStats, bool) { } // Percentiles returns percentiles results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-percentile-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-percentile-aggregation.html func (a Aggregations) Percentiles(name string) (*AggregationPercentilesMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationPercentilesMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -174,14 +205,14 @@ func (a Aggregations) Percentiles(name string) (*AggregationPercentilesMetric, b } // PercentileRanks returns percentile ranks results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-percentile-rank-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-percentile-rank-aggregation.html func (a Aggregations) PercentileRanks(name string) (*AggregationPercentilesMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationPercentilesMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -189,14 +220,14 @@ func (a Aggregations) PercentileRanks(name string) (*AggregationPercentilesMetri } // TopHits returns top-hits aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-top-hits-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-top-hits-aggregation.html func (a Aggregations) TopHits(name string) (*AggregationTopHitsMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationTopHitsMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -204,14 +235,14 @@ func (a Aggregations) TopHits(name string) (*AggregationTopHitsMetric, bool) { } // Global returns global results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-global-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-global-aggregation.html func (a Aggregations) Global(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -219,14 +250,14 @@ func (a Aggregations) Global(name string) (*AggregationSingleBucket, bool) { } // Filter returns filter results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-filter-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-filter-aggregation.html func (a Aggregations) Filter(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -234,14 +265,14 @@ func (a Aggregations) Filter(name string) (*AggregationSingleBucket, bool) { } // Filters returns filters results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-filters-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-filters-aggregation.html func (a Aggregations) Filters(name string) (*AggregationBucketFilters, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketFilters) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -249,14 +280,14 @@ func (a Aggregations) Filters(name string) (*AggregationBucketFilters, bool) { } // AdjacencyMatrix returning a form of adjacency matrix. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-adjacency-matrix-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -264,14 +295,14 @@ func (a Aggregations) AdjacencyMatrix(name string) (*AggregationBucketAdjacencyM } // Missing returns missing results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-missing-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-missing-aggregation.html func (a Aggregations) Missing(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -279,14 +310,14 @@ func (a Aggregations) Missing(name string) (*AggregationSingleBucket, bool) { } // Nested returns nested results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-nested-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-nested-aggregation.html func (a Aggregations) Nested(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -294,14 +325,14 @@ func (a Aggregations) Nested(name string) (*AggregationSingleBucket, bool) { } // ReverseNested returns reverse-nested results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-reverse-nested-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-reverse-nested-aggregation.html func (a Aggregations) ReverseNested(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -309,14 +340,14 @@ func (a Aggregations) ReverseNested(name string) (*AggregationSingleBucket, bool } // Children returns children results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-children-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-children-aggregation.html func (a Aggregations) Children(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -324,14 +355,14 @@ func (a Aggregations) Children(name string) (*AggregationSingleBucket, bool) { } // Terms returns terms aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-terms-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-terms-aggregation.html func (a Aggregations) Terms(name string) (*AggregationBucketKeyItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketKeyItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -339,14 +370,29 @@ func (a Aggregations) Terms(name string) (*AggregationBucketKeyItems, bool) { } // SignificantTerms returns significant terms aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-significantterms-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html func (a Aggregations) SignificantTerms(name string) (*AggregationBucketSignificantTerms, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketSignificantTerms) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// RareTerms returns rate terms aggregation results. +// See: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-rare-terms-aggregation.html +func (a Aggregations) RareTerms(name string) (*AggregationBucketKeyItems, bool) { + if raw, found := a[name]; found { + agg := new(AggregationBucketKeyItems) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -354,14 +400,14 @@ func (a Aggregations) SignificantTerms(name string) (*AggregationBucketSignifica } // Sampler returns sampler aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-sampler-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-sampler-aggregation.html func (a Aggregations) Sampler(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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -369,14 +415,14 @@ func (a Aggregations) Sampler(name string) (*AggregationSingleBucket, bool) { } // DiversifiedSampler returns diversified_sampler aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-diversified-sampler-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -384,14 +430,14 @@ func (a Aggregations) DiversifiedSampler(name string) (*AggregationSingleBucket, } // Range returns range aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-range-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-range-aggregation.html func (a Aggregations) Range(name string) (*AggregationBucketRangeItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketRangeItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -399,14 +445,14 @@ func (a Aggregations) Range(name string) (*AggregationBucketRangeItems, bool) { } // KeyedRange returns keyed range aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-range-aggregation.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-range-aggregation.html. func (a Aggregations) KeyedRange(name string) (*AggregationBucketKeyedRangeItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketKeyedRangeItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -414,14 +460,14 @@ func (a Aggregations) KeyedRange(name string) (*AggregationBucketKeyedRangeItems } // DateRange returns date range aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-daterange-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-daterange-aggregation.html func (a Aggregations) DateRange(name string) (*AggregationBucketRangeItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketRangeItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -429,14 +475,14 @@ func (a Aggregations) DateRange(name string) (*AggregationBucketRangeItems, bool } // IPRange returns IP range aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-iprange-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-iprange-aggregation.html func (a Aggregations) IPRange(name string) (*AggregationBucketRangeItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketRangeItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -444,14 +490,29 @@ func (a Aggregations) IPRange(name string) (*AggregationBucketRangeItems, bool) } // Histogram returns histogram aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-histogram-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-histogram-aggregation.html func (a Aggregations) Histogram(name string) (*AggregationBucketHistogramItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketHistogramItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// AutoDateHistogram returns auto date histogram aggregation results. +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html +func (a Aggregations) AutoDateHistogram(name string) (*AggregationBucketHistogramItems, bool) { + if raw, found := a[name]; found { + agg := new(AggregationBucketHistogramItems) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -459,14 +520,30 @@ func (a Aggregations) Histogram(name string) (*AggregationBucketHistogramItems, } // DateHistogram returns date histogram aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-datehistogram-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html func (a Aggregations) DateHistogram(name string) (*AggregationBucketHistogramItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketHistogramItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// KeyedDateHistogram returns date histogram aggregation results for keyed responses. +// +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html#_keyed_response_3 +func (a Aggregations) KeyedDateHistogram(name string) (*AggregationBucketKeyedHistogramItems, bool) { + if raw, found := a[name]; found { + agg := new(AggregationBucketKeyedHistogramItems) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -474,14 +551,14 @@ func (a Aggregations) DateHistogram(name string) (*AggregationBucketHistogramIte } // GeoBounds returns geo-bounds aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-geobounds-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-geobounds-aggregation.html func (a Aggregations) GeoBounds(name string) (*AggregationGeoBoundsMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationGeoBoundsMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -489,14 +566,14 @@ func (a Aggregations) GeoBounds(name string) (*AggregationGeoBoundsMetric, bool) } // GeoHash returns geo-hash aggregation results. -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-geohashgrid-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-geohashgrid-aggregation.html func (a Aggregations) GeoHash(name string) (*AggregationBucketKeyItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketKeyItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -504,14 +581,14 @@ func (a Aggregations) GeoHash(name string) (*AggregationBucketKeyItems, bool) { } // GeoCentroid returns geo-centroid aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-geocentroid-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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 { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -519,14 +596,14 @@ func (a Aggregations) GeoCentroid(name string) (*AggregationGeoCentroidMetric, b } // GeoDistance returns geo distance aggregation results. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-geodistance-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-geodistance-aggregation.html func (a Aggregations) GeoDistance(name string) (*AggregationBucketRangeItems, bool) { if raw, found := a[name]; found { agg := new(AggregationBucketRangeItems) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -534,14 +611,14 @@ 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.2/search-aggregations-pipeline-avg-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-avg-bucket-aggregation.html func (a Aggregations) AvgBucket(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -549,14 +626,14 @@ 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.2/search-aggregations-pipeline-sum-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-sum-bucket-aggregation.html func (a Aggregations) SumBucket(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -564,14 +641,14 @@ 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.2/search-aggregations-pipeline-stats-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-stats-bucket-aggregation.html func (a Aggregations) StatsBucket(name string) (*AggregationPipelineStatsMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineStatsMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -579,14 +656,14 @@ func (a Aggregations) StatsBucket(name string) (*AggregationPipelineStatsMetric, } // PercentilesBucket returns stats bucket pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-percentiles-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-percentiles-bucket-aggregation.html func (a Aggregations) PercentilesBucket(name string) (*AggregationPipelinePercentilesMetric, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelinePercentilesMetric) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -594,14 +671,14 @@ func (a Aggregations) PercentilesBucket(name string) (*AggregationPipelinePercen } // MaxBucket returns maximum bucket pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-max-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-max-bucket-aggregation.html func (a Aggregations) MaxBucket(name string) (*AggregationPipelineBucketMetricValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineBucketMetricValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -609,14 +686,14 @@ func (a Aggregations) MaxBucket(name string) (*AggregationPipelineBucketMetricVa } // MinBucket returns minimum bucket pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-min-bucket-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-min-bucket-aggregation.html func (a Aggregations) MinBucket(name string) (*AggregationPipelineBucketMetricValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineBucketMetricValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -624,14 +701,31 @@ func (a Aggregations) MinBucket(name string) (*AggregationPipelineBucketMetricVa } // MovAvg returns moving average pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-movavg-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html +// +// Deprecated: The MovAvgAggregation has been deprecated in 6.4.0. Use the more generate MovFnAggregation instead. func (a Aggregations) MovAvg(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// MovFn returns moving function pipeline aggregation results. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movfn-aggregation.html +func (a Aggregations) MovFn(name string) (*AggregationPipelineSimpleValue, bool) { + if raw, found := a[name]; found { + agg := new(AggregationPipelineSimpleValue) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -639,14 +733,14 @@ func (a Aggregations) MovAvg(name string) (*AggregationPipelineSimpleValue, bool } // Derivative returns derivative pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-derivative-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-derivative-aggregation.html func (a Aggregations) Derivative(name string) (*AggregationPipelineDerivative, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineDerivative) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -654,14 +748,14 @@ 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.2/search-aggregations-pipeline-cumulative-sum-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-cumulative-sum-aggregation.html func (a Aggregations) CumulativeSum(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -669,14 +763,14 @@ func (a Aggregations) CumulativeSum(name string) (*AggregationPipelineSimpleValu } // BucketScript returns bucket script pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-bucket-script-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-bucket-script-aggregation.html func (a Aggregations) BucketScript(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -684,14 +778,14 @@ func (a Aggregations) BucketScript(name string) (*AggregationPipelineSimpleValue } // SerialDiff returns serial differencing pipeline aggregation results. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-serialdiff-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-serialdiff-aggregation.html func (a Aggregations) SerialDiff(name string) (*AggregationPipelineSimpleValue, bool) { if raw, found := a[name]; found { agg := new(AggregationPipelineSimpleValue) if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -700,7 +794,7 @@ func (a Aggregations) SerialDiff(name string) (*AggregationPipelineSimpleValue, // Composite returns composite bucket aggregation results. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-composite-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html // for details. func (a Aggregations) Composite(name string) (*AggregationBucketCompositeItems, bool) { if raw, found := a[name]; found { @@ -708,7 +802,23 @@ func (a Aggregations) Composite(name string) (*AggregationBucketCompositeItems, if raw == nil { return agg, true } - if err := json.Unmarshal(*raw, agg); err == nil { + if err := json.Unmarshal(raw, agg); err == nil { + return agg, true + } + } + return nil, false +} + +// ScriptedMetric returns scripted metric aggregation results. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.2/search-aggregations-metrics-scripted-metric-aggregation.html +// for details. +func (a Aggregations) ScriptedMetric(name string) (*AggregationScriptedMetric, bool) { + if raw, found := a[name]; found { + agg := new(AggregationScriptedMetric) + if raw == nil { + return agg, true + } + if err := json.Unmarshal(raw, agg); err == nil { return agg, true } } @@ -728,15 +838,15 @@ type AggregationValueMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationValueMetric structure. func (a *AggregationValueMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["value"]; ok && v != nil { - json.Unmarshal(*v, &a.Value) + json.Unmarshal(v, &a.Value) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -758,27 +868,27 @@ type AggregationStatsMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationStatsMetric structure. func (a *AggregationStatsMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["count"]; ok && v != nil { - json.Unmarshal(*v, &a.Count) + json.Unmarshal(v, &a.Count) } if v, ok := aggs["min"]; ok && v != nil { - json.Unmarshal(*v, &a.Min) + json.Unmarshal(v, &a.Min) } if v, ok := aggs["max"]; ok && v != nil { - json.Unmarshal(*v, &a.Max) + json.Unmarshal(v, &a.Max) } if v, ok := aggs["avg"]; ok && v != nil { - json.Unmarshal(*v, &a.Avg) + json.Unmarshal(v, &a.Avg) } if v, ok := aggs["sum"]; ok && v != nil { - json.Unmarshal(*v, &a.Sum) + json.Unmarshal(v, &a.Sum) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -803,36 +913,36 @@ type AggregationExtendedStatsMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationExtendedStatsMetric structure. func (a *AggregationExtendedStatsMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["count"]; ok && v != nil { - json.Unmarshal(*v, &a.Count) + json.Unmarshal(v, &a.Count) } if v, ok := aggs["min"]; ok && v != nil { - json.Unmarshal(*v, &a.Min) + json.Unmarshal(v, &a.Min) } if v, ok := aggs["max"]; ok && v != nil { - json.Unmarshal(*v, &a.Max) + json.Unmarshal(v, &a.Max) } if v, ok := aggs["avg"]; ok && v != nil { - json.Unmarshal(*v, &a.Avg) + json.Unmarshal(v, &a.Avg) } if v, ok := aggs["sum"]; ok && v != nil { - json.Unmarshal(*v, &a.Sum) + json.Unmarshal(v, &a.Sum) } if v, ok := aggs["sum_of_squares"]; ok && v != nil { - json.Unmarshal(*v, &a.SumOfSquares) + json.Unmarshal(v, &a.SumOfSquares) } if v, ok := aggs["variance"]; ok && v != nil { - json.Unmarshal(*v, &a.Variance) + json.Unmarshal(v, &a.Variance) } if v, ok := aggs["std_deviation"]; ok && v != nil { - json.Unmarshal(*v, &a.StdDeviation) + json.Unmarshal(v, &a.StdDeviation) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -863,16 +973,16 @@ type AggregationMatrixStatsField struct { // UnmarshalJSON decodes JSON data and initializes an AggregationMatrixStats structure. func (a *AggregationMatrixStats) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["fields"]; ok && v != nil { // RunningStats for every field - json.Unmarshal(*v, &a.Fields) + json.Unmarshal(v, &a.Fields) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -890,15 +1000,15 @@ type AggregationPercentilesMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPercentilesMetric structure. func (a *AggregationPercentilesMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["values"]; ok && v != nil { - json.Unmarshal(*v, &a.Values) + json.Unmarshal(v, &a.Values) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -916,17 +1026,17 @@ type AggregationTopHitsMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationTopHitsMetric structure. func (a *AggregationTopHitsMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } a.Aggregations = aggs a.Hits = new(SearchHits) if v, ok := aggs["hits"]; ok && v != nil { - json.Unmarshal(*v, &a.Hits) + json.Unmarshal(v, &a.Hits) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } return nil } @@ -953,15 +1063,15 @@ type AggregationGeoBoundsMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationGeoBoundsMetric structure. func (a *AggregationGeoBoundsMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["bounds"]; ok && v != nil { - json.Unmarshal(*v, &a.Bounds) + json.Unmarshal(v, &a.Bounds) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -983,18 +1093,18 @@ type AggregationGeoCentroidMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationGeoCentroidMetric structure. func (a *AggregationGeoCentroidMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) + json.Unmarshal(v, &a.Location) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } if v, ok := aggs["count"]; ok && v != nil { - json.Unmarshal(*v, &a.Count) + json.Unmarshal(v, &a.Count) } a.Aggregations = aggs return nil @@ -1012,15 +1122,15 @@ type AggregationSingleBucket struct { // UnmarshalJSON decodes JSON data and initializes an AggregationSingleBucket structure. func (a *AggregationSingleBucket) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1041,21 +1151,21 @@ type AggregationBucketRangeItems struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure. func (a *AggregationBucketRangeItems) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["doc_count_error_upper_bound"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCountErrorUpperBound) + json.Unmarshal(v, &a.DocCountErrorUpperBound) } if v, ok := aggs["sum_other_doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.SumOfOtherDocCount) + json.Unmarshal(v, &a.SumOfOtherDocCount) } if v, ok := aggs["buckets"]; ok && v != nil { - json.Unmarshal(*v, &a.Buckets) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1074,21 +1184,21 @@ type AggregationBucketKeyedRangeItems struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure. func (a *AggregationBucketKeyedRangeItems) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["doc_count_error_upper_bound"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCountErrorUpperBound) + json.Unmarshal(v, &a.DocCountErrorUpperBound) } if v, ok := aggs["sum_other_doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.SumOfOtherDocCount) + json.Unmarshal(v, &a.SumOfOtherDocCount) } if v, ok := aggs["buckets"]; ok && v != nil { - json.Unmarshal(*v, &a.Buckets) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1108,27 +1218,27 @@ type AggregationBucketRangeItem struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItem structure. func (a *AggregationBucketRangeItem) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["key"]; ok && v != nil { - json.Unmarshal(*v, &a.Key) + json.Unmarshal(v, &a.Key) } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } if v, ok := aggs["from"]; ok && v != nil { - json.Unmarshal(*v, &a.From) + json.Unmarshal(v, &a.From) } if v, ok := aggs["from_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.FromAsString) + json.Unmarshal(v, &a.FromAsString) } if v, ok := aggs["to"]; ok && v != nil { - json.Unmarshal(*v, &a.To) + json.Unmarshal(v, &a.To) } if v, ok := aggs["to_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.ToAsString) + json.Unmarshal(v, &a.ToAsString) } a.Aggregations = aggs return nil @@ -1149,21 +1259,21 @@ type AggregationBucketKeyItems struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItems structure. func (a *AggregationBucketKeyItems) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["doc_count_error_upper_bound"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCountErrorUpperBound) + json.Unmarshal(v, &a.DocCountErrorUpperBound) } if v, ok := aggs["sum_other_doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.SumOfOtherDocCount) + json.Unmarshal(v, &a.SumOfOtherDocCount) } if v, ok := aggs["buckets"]; ok && v != nil { - json.Unmarshal(*v, &a.Buckets) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1181,21 +1291,21 @@ type AggregationBucketKeyItem struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItem structure. func (a *AggregationBucketKeyItem) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) - json.Unmarshal(*v, &a.KeyNumber) + json.Unmarshal(v, &a.Key) + json.Unmarshal(v, &a.KeyNumber) } if v, ok := aggs["key_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.KeyAsString) + json.Unmarshal(v, &a.KeyAsString) } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } a.Aggregations = aggs return nil @@ -1215,18 +1325,18 @@ type AggregationBucketSignificantTerms struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerms structure. func (a *AggregationBucketSignificantTerms) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } if v, ok := aggs["buckets"]; ok && v != nil { - json.Unmarshal(*v, &a.Buckets) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1244,21 +1354,21 @@ type AggregationBucketSignificantTerm struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerm structure. func (a *AggregationBucketSignificantTerm) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["key"]; ok && v != nil { - json.Unmarshal(*v, &a.Key) + json.Unmarshal(v, &a.Key) } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } if v, ok := aggs["bg_count"]; ok && v != nil { - json.Unmarshal(*v, &a.BgCount) + json.Unmarshal(v, &a.BgCount) } if v, ok := aggs["score"]; ok && v != nil { - json.Unmarshal(*v, &a.Score) + json.Unmarshal(v, &a.Score) } a.Aggregations = aggs return nil @@ -1278,16 +1388,16 @@ type AggregationBucketFilters struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketFilters structure. func (a *AggregationBucketFilters) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) - json.Unmarshal(*v, &a.NamedBuckets) + json.Unmarshal(v, &a.Buckets) + json.Unmarshal(v, &a.NamedBuckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1306,15 +1416,15 @@ type AggregationBucketAdjacencyMatrix struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketAdjacencyMatrix structure. func (a *AggregationBucketAdjacencyMatrix) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1327,21 +1437,46 @@ func (a *AggregationBucketAdjacencyMatrix) UnmarshalJSON(data []byte) error { type AggregationBucketHistogramItems struct { Aggregations - Buckets []*AggregationBucketHistogramItem //`json:"buckets"` + Buckets []*AggregationBucketHistogramItem // `json:"buckets"` Meta map[string]interface{} // `json:"meta,omitempty"` } // UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItems structure. func (a *AggregationBucketHistogramItems) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) + } + a.Aggregations = aggs + return nil +} + +// AggregationBucketKeyedHistogramItems is a bucket aggregation that is returned +// with a (keyed) date histogram aggregation. +type AggregationBucketKeyedHistogramItems struct { + Aggregations + + Buckets map[string]*AggregationBucketHistogramItem //`json:"buckets"` + Meta map[string]interface{} // `json:"meta,omitempty"` +} + +// UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyedHistogramItems structure. +func (a *AggregationBucketKeyedHistogramItems) 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 @@ -1358,18 +1493,18 @@ type AggregationBucketHistogramItem struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItem structure. func (a *AggregationBucketHistogramItem) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["key"]; ok && v != nil { - json.Unmarshal(*v, &a.Key) + json.Unmarshal(v, &a.Key) } if v, ok := aggs["key_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.KeyAsString) + json.Unmarshal(v, &a.KeyAsString) } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) } a.Aggregations = aggs return nil @@ -1389,18 +1524,18 @@ type AggregationPipelineSimpleValue struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPipelineSimpleValue structure. func (a *AggregationPipelineSimpleValue) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["value"]; ok && v != nil { - json.Unmarshal(*v, &a.Value) + json.Unmarshal(v, &a.Value) } if v, ok := aggs["value_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.ValueAsString) + json.Unmarshal(v, &a.ValueAsString) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1421,21 +1556,21 @@ type AggregationPipelineBucketMetricValue struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPipelineBucketMetricValue structure. func (a *AggregationPipelineBucketMetricValue) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["keys"]; ok && v != nil { - json.Unmarshal(*v, &a.Keys) + json.Unmarshal(v, &a.Keys) } if v, ok := aggs["value"]; ok && v != nil { - json.Unmarshal(*v, &a.Value) + json.Unmarshal(v, &a.Value) } if v, ok := aggs["value_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.ValueAsString) + json.Unmarshal(v, &a.ValueAsString) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1457,24 +1592,24 @@ type AggregationPipelineDerivative struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPipelineDerivative structure. func (a *AggregationPipelineDerivative) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["value"]; ok && v != nil { - json.Unmarshal(*v, &a.Value) + json.Unmarshal(v, &a.Value) } if v, ok := aggs["value_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.ValueAsString) + json.Unmarshal(v, &a.ValueAsString) } if v, ok := aggs["normalized_value"]; ok && v != nil { - json.Unmarshal(*v, &a.NormalizedValue) + json.Unmarshal(v, &a.NormalizedValue) } if v, ok := aggs["normalized_value_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.NormalizedValueAsString) + json.Unmarshal(v, &a.NormalizedValueAsString) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1503,42 +1638,42 @@ type AggregationPipelineStatsMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPipelineStatsMetric structure. func (a *AggregationPipelineStatsMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["count"]; ok && v != nil { - json.Unmarshal(*v, &a.Count) + json.Unmarshal(v, &a.Count) } if v, ok := aggs["count_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.CountAsString) + json.Unmarshal(v, &a.CountAsString) } if v, ok := aggs["min"]; ok && v != nil { - json.Unmarshal(*v, &a.Min) + json.Unmarshal(v, &a.Min) } if v, ok := aggs["min_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.MinAsString) + json.Unmarshal(v, &a.MinAsString) } if v, ok := aggs["max"]; ok && v != nil { - json.Unmarshal(*v, &a.Max) + json.Unmarshal(v, &a.Max) } if v, ok := aggs["max_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.MaxAsString) + json.Unmarshal(v, &a.MaxAsString) } if v, ok := aggs["avg"]; ok && v != nil { - json.Unmarshal(*v, &a.Avg) + json.Unmarshal(v, &a.Avg) } if v, ok := aggs["avg_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.AvgAsString) + json.Unmarshal(v, &a.AvgAsString) } if v, ok := aggs["sum"]; ok && v != nil { - json.Unmarshal(*v, &a.Sum) + json.Unmarshal(v, &a.Sum) } if v, ok := aggs["sum_as_string"]; ok && v != nil { - json.Unmarshal(*v, &a.SumAsString) + json.Unmarshal(v, &a.SumAsString) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1557,15 +1692,15 @@ type AggregationPipelinePercentilesMetric struct { // UnmarshalJSON decodes JSON data and initializes an AggregationPipelinePercentilesMetric structure. func (a *AggregationPipelinePercentilesMetric) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + var aggs map[string]json.RawMessage if err := json.Unmarshal(data, &aggs); err != nil { return err } if v, ok := aggs["values"]; ok && v != nil { - json.Unmarshal(*v, &a.Values) + json.Unmarshal(v, &a.Values) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil @@ -1578,21 +1713,25 @@ func (a *AggregationPipelinePercentilesMetric) UnmarshalJSON(data []byte) error type AggregationBucketCompositeItems struct { Aggregations - Buckets []*AggregationBucketCompositeItem //`json:"buckets"` - Meta map[string]interface{} // `json:"meta,omitempty"` + Buckets []*AggregationBucketCompositeItem //`json:"buckets"` + Meta map[string]interface{} // `json:"meta,omitempty"` + AfterKey map[string]interface{} // `json:"after_key,omitempty"` } // UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItems structure. func (a *AggregationBucketCompositeItems) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) + json.Unmarshal(v, &a.Buckets) } if v, ok := aggs["meta"]; ok && v != nil { - json.Unmarshal(*v, &a.Meta) + json.Unmarshal(v, &a.Meta) + } + if v, ok := aggs["after_key"]; ok && v != nil { + json.Unmarshal(v, &a.AfterKey) } a.Aggregations = aggs return nil @@ -1608,17 +1747,44 @@ type AggregationBucketCompositeItem struct { // UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItem structure. func (a *AggregationBucketCompositeItem) UnmarshalJSON(data []byte) error { - var aggs map[string]*json.RawMessage + 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) + json.Unmarshal(v, &a.Key) } if v, ok := aggs["doc_count"]; ok && v != nil { - json.Unmarshal(*v, &a.DocCount) + json.Unmarshal(v, &a.DocCount) + } + a.Aggregations = aggs + return nil +} + +// AggregationScriptedMetric is the value return by a scripted metric aggregation. +// Value maybe one of map[string]interface{}/[]interface{}/string/bool/json.Number +type AggregationScriptedMetric struct { + Aggregations + + Value interface{} //`json:"value"` + Meta map[string]interface{} //`json:"meta,omitempty"` +} + +// UnmarshalJSON decodes JSON data and initializes an AggregationScriptedMetric structure. +func (a *AggregationScriptedMetric) UnmarshalJSON(data []byte) error { + var aggs map[string]json.RawMessage + if err := json.Unmarshal(data, &aggs); err != nil { + return err + } + if v, ok := aggs["value"]; ok && v != nil { + decoder := json.NewDecoder(bytes.NewReader(v)) + decoder.UseNumber() + decoder.Decode(&a.Value) + } + if v, ok := aggs["meta"]; ok && v != nil { + json.Unmarshal(v, &a.Meta) } a.Aggregations = aggs return nil diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_adjacency_matrix.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_adjacency_matrix.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_adjacency_matrix.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_adjacency_matrix.go index 24ccee2..7dff0e0 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_adjacency_matrix.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_adjacency_matrix.go @@ -10,7 +10,7 @@ package elastic // response represents a non-empty cell in the matrix of intersecting filters. // // For details, see -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-adjacency-matrix-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-adjacency-matrix-aggregation.html type AdjacencyMatrixAggregation struct { filters map[string]Query subAggregations map[string]Aggregation diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_auto_date_histogram.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_auto_date_histogram.go new file mode 100644 index 0000000..281ee23 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_auto_date_histogram.go @@ -0,0 +1,163 @@ +// 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 + +// AutoDateHistogramAggregation is a multi-bucket aggregation similar to the +// histogram except it can only be applied on date values, and the buckets num can bin pointed. +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-aggregations-bucket-autodatehistogram-aggregation.html +type AutoDateHistogramAggregation struct { + field string + script *Script + missing interface{} + subAggregations map[string]Aggregation + meta map[string]interface{} + + buckets int + minDocCount *int64 + timeZone string + format string + minimumInterval string +} + +// NewAutoDateHistogramAggregation creates a new AutoDateHistogramAggregation. +func NewAutoDateHistogramAggregation() *AutoDateHistogramAggregation { + return &AutoDateHistogramAggregation{ + subAggregations: make(map[string]Aggregation), + } +} + +// Field on which the aggregation is processed. +func (a *AutoDateHistogramAggregation) Field(field string) *AutoDateHistogramAggregation { + a.field = field + return a +} + +// Script on which th +func (a *AutoDateHistogramAggregation) Script(script *Script) *AutoDateHistogramAggregation { + a.script = script + return a +} + +// Missing configures the value to use when documents miss a value. +func (a *AutoDateHistogramAggregation) Missing(missing interface{}) *AutoDateHistogramAggregation { + a.missing = missing + return a +} + +// SubAggregation sub aggregation +func (a *AutoDateHistogramAggregation) SubAggregation(name string, subAggregation Aggregation) *AutoDateHistogramAggregation { + a.subAggregations[name] = subAggregation + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *AutoDateHistogramAggregation) Meta(metaData map[string]interface{}) *AutoDateHistogramAggregation { + a.meta = metaData + return a +} + +// Buckets buckets num by which the aggregation gets processed. +func (a *AutoDateHistogramAggregation) Buckets(buckets int) *AutoDateHistogramAggregation { + a.buckets = buckets + return a +} + +// MinDocCount sets the minimum document count per bucket. +// Buckets with less documents than this min value will not be returned. +func (a *AutoDateHistogramAggregation) MinDocCount(minDocCount int64) *AutoDateHistogramAggregation { + a.minDocCount = &minDocCount + return a +} + +// TimeZone sets the timezone in which to translate dates before computing buckets. +func (a *AutoDateHistogramAggregation) TimeZone(timeZone string) *AutoDateHistogramAggregation { + a.timeZone = timeZone + return a +} + +// Format sets the format to use for dates. +func (a *AutoDateHistogramAggregation) Format(format string) *AutoDateHistogramAggregation { + a.format = format + return a +} + +// MinimumInterval accepted units for minimum_interval are: year/month/day/hour/minute/second +func (a *AutoDateHistogramAggregation) MinimumInterval(interval string) *AutoDateHistogramAggregation { + a.minimumInterval = interval + return a +} + +// Source source for AutoDateHistogramAggregation +func (a *AutoDateHistogramAggregation) Source() (interface{}, error) { + // Example: + // { + // "aggs" : { + // "articles_over_time" : { + // "auto_date_histogram" : { + // "field" : "date", + // "buckets" : 10 + // } + // } + // } + // } + // + // This method returns only the { "auto_date_histogram" : { ... } } part. + + source := make(map[string]interface{}) + opts := make(map[string]interface{}) + source["auto_date_histogram"] = opts + + // ValuesSourceAggregationBuilder + 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.missing != nil { + opts["missing"] = a.missing + } + + if a.buckets > 0 { + opts["buckets"] = a.buckets + } + + if a.minDocCount != nil { + opts["min_doc_count"] = *a.minDocCount + } + if a.timeZone != "" { + opts["time_zone"] = a.timeZone + } + if a.format != "" { + opts["format"] = a.format + } + if a.minimumInterval != "" { + opts["minimum_interval"] = a.minimumInterval + } + + // 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.v6/search_aggs_bucket_children.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_children.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_children.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_children.go index 1a948c3..4078b1d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_children.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-children-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-children-aggregation.html type ChildrenAggregation struct { typ string subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_composite.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_composite.go similarity index 78% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_composite.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_composite.go index 98a48e2..859c9e4 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_composite.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_composite.go @@ -7,7 +7,7 @@ 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.2/search-aggregations-bucket-composite-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html // for details. type CompositeAggregation struct { after map[string]interface{} @@ -129,7 +129,7 @@ func (a *CompositeAggregation) Source() (interface{}, error) { // need to implement. // // The different implementations are described in -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-composite-aggregation.html#_values_source_2. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html#_values_source_2. type CompositeAggregationValuesSource interface { Source() (interface{}, error) } @@ -139,15 +139,16 @@ type CompositeAggregationValuesSource interface { // 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.2/search-aggregations-bucket-composite-aggregation.html#_terms +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html#_terms // for details. type CompositeAggregationTermsValuesSource struct { - name string - field string - script *Script - valueType string - missing interface{} - order string + name string + field string + script *Script + valueType string + missing interface{} + missingBucket *bool + order string } // NewCompositeAggregationTermsValuesSource creates and initializes @@ -198,11 +199,20 @@ func (a *CompositeAggregationTermsValuesSource) Desc() *CompositeAggregationTerm // Missing specifies the value to use when the source finds a missing // value in a document. +// +// Deprecated: Use MissingBucket instead. func (a *CompositeAggregationTermsValuesSource) Missing(missing interface{}) *CompositeAggregationTermsValuesSource { a.missing = missing return a } +// MissingBucket, if true, will create an explicit null bucket which represents +// documents with missing values. +func (a *CompositeAggregationTermsValuesSource) MissingBucket(missingBucket bool) *CompositeAggregationTermsValuesSource { + a.missingBucket = &missingBucket + return a +} + // Source returns the serializable JSON for this values source. func (a *CompositeAggregationTermsValuesSource) Source() (interface{}, error) { source := make(map[string]interface{}) @@ -230,6 +240,11 @@ func (a *CompositeAggregationTermsValuesSource) Source() (interface{}, error) { values["missing"] = a.missing } + // missing_bucket + if a.missingBucket != nil { + values["missing_bucket"] = *a.missingBucket + } + // value_type if a.valueType != "" { values["value_type"] = a.valueType @@ -249,16 +264,17 @@ func (a *CompositeAggregationTermsValuesSource) Source() (interface{}, error) { // 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.2/search-aggregations-bucket-composite-aggregation.html#_histogram +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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 + name string + field string + script *Script + valueType string + missing interface{} + missingBucket *bool + order string + interval float64 } // NewCompositeAggregationHistogramValuesSource creates and initializes @@ -291,11 +307,20 @@ func (a *CompositeAggregationHistogramValuesSource) ValueType(valueType string) // Missing specifies the value to use when the source finds a missing // value in a document. +// +// Deprecated: Use MissingBucket instead. func (a *CompositeAggregationHistogramValuesSource) Missing(missing interface{}) *CompositeAggregationHistogramValuesSource { a.missing = missing return a } +// MissingBucket, if true, will create an explicit null bucket which represents +// documents with missing values. +func (a *CompositeAggregationHistogramValuesSource) MissingBucket(missingBucket bool) *CompositeAggregationHistogramValuesSource { + a.missingBucket = &missingBucket + 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 { @@ -348,6 +373,11 @@ func (a *CompositeAggregationHistogramValuesSource) Source() (interface{}, error values["missing"] = a.missing } + // missing_bucket + if a.missingBucket != nil { + values["missing_bucket"] = *a.missingBucket + } + // value_type if a.valueType != "" { values["value_type"] = a.valueType @@ -370,25 +400,28 @@ func (a *CompositeAggregationHistogramValuesSource) Source() (interface{}, error // 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.2/search-aggregations-bucket-composite-aggregation.html#_date_histogram +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/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 + name string + field string + script *Script + valueType string + missing interface{} + missingBucket *bool + order string + interval interface{} + fixedInterval interface{} + calendarInterval interface{} + format string + timeZone string } // NewCompositeAggregationDateHistogramValuesSource creates and initializes // a new CompositeAggregationDateHistogramValuesSource. -func NewCompositeAggregationDateHistogramValuesSource(name string, interval interface{}) *CompositeAggregationDateHistogramValuesSource { +func NewCompositeAggregationDateHistogramValuesSource(name string) *CompositeAggregationDateHistogramValuesSource { return &CompositeAggregationDateHistogramValuesSource{ - name: name, - interval: interval, + name: name, } } @@ -413,11 +446,20 @@ func (a *CompositeAggregationDateHistogramValuesSource) ValueType(valueType stri // Missing specifies the value to use when the source finds a missing // value in a document. +// +// Deprecated: Use MissingBucket instead. func (a *CompositeAggregationDateHistogramValuesSource) Missing(missing interface{}) *CompositeAggregationDateHistogramValuesSource { a.missing = missing return a } +// MissingBucket, if true, will create an explicit null bucket which represents +// documents with missing values. +func (a *CompositeAggregationDateHistogramValuesSource) MissingBucket(missingBucket bool) *CompositeAggregationDateHistogramValuesSource { + a.missingBucket = &missingBucket + 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 { @@ -438,11 +480,31 @@ func (a *CompositeAggregationDateHistogramValuesSource) Desc() *CompositeAggrega } // Interval to use for the date histogram, e.g. "1d" or a numeric value like "60". +// +// Deprecated: Use FixedInterval or CalendarInterval instead. func (a *CompositeAggregationDateHistogramValuesSource) Interval(interval interface{}) *CompositeAggregationDateHistogramValuesSource { a.interval = interval return a } +// FixedInterval to use for the date histogram, e.g. "1d" or a numeric value like "60". +func (a *CompositeAggregationDateHistogramValuesSource) FixedInterval(fixedInterval interface{}) *CompositeAggregationDateHistogramValuesSource { + a.fixedInterval = fixedInterval + return a +} + +// CalendarInterval to use for the date histogram, e.g. "1d" or a numeric value like "60". +func (a *CompositeAggregationDateHistogramValuesSource) CalendarInterval(calendarInterval interface{}) *CompositeAggregationDateHistogramValuesSource { + a.calendarInterval = calendarInterval + return a +} + +// Format to use for the date histogram, e.g. "strict_date_optional_time" +func (a *CompositeAggregationDateHistogramValuesSource) Format(format string) *CompositeAggregationDateHistogramValuesSource { + a.format = format + return a +} + // TimeZone to use for the dates. func (a *CompositeAggregationDateHistogramValuesSource) TimeZone(timeZone string) *CompositeAggregationDateHistogramValuesSource { a.timeZone = timeZone @@ -476,6 +538,11 @@ func (a *CompositeAggregationDateHistogramValuesSource) Source() (interface{}, e values["missing"] = a.missing } + // missing_bucket + if a.missingBucket != nil { + values["missing_bucket"] = *a.missingBucket + } + // value_type if a.valueType != "" { values["value_type"] = a.valueType @@ -486,8 +553,20 @@ func (a *CompositeAggregationDateHistogramValuesSource) Source() (interface{}, e values["order"] = a.order } + if a.format != "" { + values["format"] = a.format + } + // DateHistogram-related properties - values["interval"] = a.interval + if v := a.interval; v != nil { + values["interval"] = v + } + if v := a.fixedInterval; v != nil { + values["fixed_interval"] = v + } + if v := a.calendarInterval; v != nil { + values["calendar_interval"] = v + } // timeZone if a.timeZone != "" { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_count_thresholds.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_count_thresholds.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_count_thresholds.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_count_thresholds.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_histogram.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_histogram.go similarity index 76% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_histogram.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_histogram.go index 881da22..4ab567c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_histogram.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-datehistogram-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html type DateHistogramAggregation struct { field string script *Script @@ -15,6 +15,8 @@ type DateHistogramAggregation struct { meta map[string]interface{} interval string + fixedInterval string + calendarInterval string order string orderAsc bool minDocCount *int64 @@ -23,6 +25,7 @@ type DateHistogramAggregation struct { timeZone string format string offset string + keyed *bool } // NewDateHistogramAggregation creates a new DateHistogramAggregation. @@ -60,15 +63,48 @@ func (a *DateHistogramAggregation) Meta(metaData map[string]interface{}) *DateHi return a } -// Interval by which the aggregation gets processed. -// Allowed values are: "year", "quarter", "month", "week", "day", -// "hour", "minute". It also supports time settings like "1.5h" -// (up to "w" for weeks). +// Interval by which the aggregation gets processed. This field +// will be replaced by the two FixedInterval and CalendarInterval +// fields (see below). +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-aggregations-bucket-datehistogram-aggregation.html +// +// Deprecated: This field will be removed in the future. func (a *DateHistogramAggregation) Interval(interval string) *DateHistogramAggregation { a.interval = interval return a } +// FixedInterval by which the aggregation gets processed. +// +// Allowed values are: "year", "1y", "quarter", "1q", "month", "1M", +// "week", "1w", "day", "1d", "hour", "1h", "minute", "1m", "second", +// or "1s". It also supports time settings like "1.5h". +// +// These units are not calendar-aware and are simply multiples of +// fixed, SI units. This is mutually exclusive with CalendarInterval. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-aggregations-bucket-datehistogram-aggregation.html +func (a *DateHistogramAggregation) FixedInterval(fixedInterval string) *DateHistogramAggregation { + a.fixedInterval = fixedInterval + return a +} + +// CalendarInterval by which the aggregation gets processed. +// +// Allowed values are: "year" ("1y", "y"), "quarter" ("1q", "q"), +// "month" ("1M", "M"), "week" ("1w", "w"), "day" ("d", "1d") +// +// These units are calendar-aware, meaning they respect leap +// additions, variable days per month etc. This is mutually +// exclusive with FixedInterval. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-aggregations-bucket-datehistogram-aggregation.html +func (a *DateHistogramAggregation) CalendarInterval(calendarInterval string) *DateHistogramAggregation { + a.calendarInterval = calendarInterval + return a +} + // Order specifies the sort order. Valid values for order are: // "_key", "_count", a sub-aggregation name, or a sub-aggregation name // with a metric. @@ -196,6 +232,14 @@ func (a *DateHistogramAggregation) ExtendedBoundsMax(max interface{}) *DateHisto return a } +// Keyed specifies whether to return the results with a keyed response (or not). +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html#_keyed_response_3. +func (a *DateHistogramAggregation) Keyed(keyed bool) *DateHistogramAggregation { + a.keyed = &keyed + return a +} + func (a *DateHistogramAggregation) Source() (interface{}, error) { // Example: // { @@ -203,7 +247,7 @@ func (a *DateHistogramAggregation) Source() (interface{}, error) { // "articles_over_time" : { // "date_histogram" : { // "field" : "date", - // "interval" : "month" + // "fixed_interval" : "month" // } // } // } @@ -230,7 +274,16 @@ func (a *DateHistogramAggregation) Source() (interface{}, error) { opts["missing"] = a.missing } - opts["interval"] = a.interval + if s := a.interval; s != "" { + opts["interval"] = s + } + if s := a.fixedInterval; s != "" { + opts["fixed_interval"] = s + } + if s := a.calendarInterval; s != "" { + opts["calendar_interval"] = s + } + if a.minDocCount != nil { opts["min_doc_count"] = *a.minDocCount } @@ -262,6 +315,9 @@ func (a *DateHistogramAggregation) Source() (interface{}, error) { } opts["extended_bounds"] = bounds } + if a.keyed != nil { + opts["keyed"] = *a.keyed + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_range.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_range.go similarity index 99% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_range.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_range.go index 97cc147..a4becaa 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_date_range.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-daterange-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-daterange-aggregation.html type DateRangeAggregation struct { field string script *Script diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_diversified_sampler.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_diversified_sampler.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_diversified_sampler.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_diversified_sampler.go index ef7a696..6d3a448 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_diversified_sampler.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_diversified_sampler.go @@ -8,7 +8,7 @@ package elastic // 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/6.2/search-aggregations-bucket-diversified-sampler-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-diversified-sampler-aggregation.html type DiversifiedSamplerAggregation struct { subAggregations map[string]Aggregation meta map[string]interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filter.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filter.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filter.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filter.go index 40acdee..c002c81 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filter.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-filter-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-filter-aggregation.html type FilterAggregation struct { filter Query subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filters.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filters.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filters.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filters.go index 8f1f289..d2ea5ea 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_filters.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-filters-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-filters-aggregation.html type FiltersAggregation struct { unnamedFilters []Query namedFilters map[string]Query diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geo_distance.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geo_distance.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geo_distance.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geo_distance.go index c4a59e8..ee8dd0c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geo_distance.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-geodistance-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-geodistance-aggregation.html type GeoDistanceAggregation struct { field string unit string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geohash_grid.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geohash_grid.go similarity index 94% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geohash_grid.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geohash_grid.go index 4c3e945..1a56b57 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_geohash_grid.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geohash_grid.go @@ -23,8 +23,8 @@ func (a *GeoHashGridAggregation) Field(field string) *GeoHashGridAggregation { } // Precision accepts the level as int value between 1 and 12 or Distance Units like "2km", "5mi" as described at -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/common-options.html#distance-units and -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-geohashgrid-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/common-options.html#distance-units and +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-geohashgrid-aggregation.html func (a *GeoHashGridAggregation) Precision(precision interface{}) *GeoHashGridAggregation { a.precision = precision return a diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_global.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_global.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_global.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_global.go index 961f6dd..2e07f5d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_global.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-global-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.v6/search_aggs_bucket_histogram.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_histogram.go similarity index 99% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_histogram.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_histogram.go index 16c53fb..69021e6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_histogram.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-histogram-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-histogram-aggregation.html type HistogramAggregation struct { field string script *Script diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_ip_range.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_ip_range.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_ip_range.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_ip_range.go index 08b4f7d..76ebe0d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_ip_range.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-iprange-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-iprange-aggregation.html type IPRangeAggregation struct { field string subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_missing.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_missing.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_missing.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_missing.go index 182f4e3..68eba98 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_missing.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-missing-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-missing-aggregation.html type MissingAggregation struct { field string subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_nested.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_nested.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_nested.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_nested.go index 8b444b0..5481f92 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_nested.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-nested-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-nested-aggregation.html type NestedAggregation struct { path string subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_range.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_range.go similarity index 99% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_range.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_range.go index 94a71c9..7e786d9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_range.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-range-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-range-aggregation.html type RangeAggregation struct { field string script *Script diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_rare_terms.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_rare_terms.go new file mode 100644 index 0000000..4d77bbc --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_rare_terms.go @@ -0,0 +1,156 @@ +// 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 + +// RareTermsAggregation is a multi-bucket value source based aggregation +// which finds "rare" terms — terms that are at the long-tail of the distribution +// and are not frequent. Conceptually, this is like a terms aggregation that +// is sorted by _count ascending. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-rare-terms-aggregation.html +// for details. +type RareTermsAggregation struct { + field string + subAggregations map[string]Aggregation + meta map[string]interface{} + + includeExclude *TermsAggregationIncludeExclude + maxDocCount *int + precision *float64 + missing interface{} +} + +func NewRareTermsAggregation() *RareTermsAggregation { + return &RareTermsAggregation{ + subAggregations: make(map[string]Aggregation), + } +} + +func (a *RareTermsAggregation) Field(field string) *RareTermsAggregation { + a.field = field + return a +} + +func (a *RareTermsAggregation) SubAggregation(name string, subAggregation Aggregation) *RareTermsAggregation { + a.subAggregations[name] = subAggregation + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *RareTermsAggregation) Meta(metaData map[string]interface{}) *RareTermsAggregation { + a.meta = metaData + return a +} + +func (a *RareTermsAggregation) MaxDocCount(maxDocCount int) *RareTermsAggregation { + a.maxDocCount = &maxDocCount + return a +} + +func (a *RareTermsAggregation) Precision(precision float64) *RareTermsAggregation { + a.precision = &precision + return a +} + +func (a *RareTermsAggregation) Missing(missing interface{}) *RareTermsAggregation { + a.missing = missing + return a +} + +func (a *RareTermsAggregation) Include(regexp string) *RareTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.Include = regexp + return a +} + +func (a *RareTermsAggregation) IncludeValues(values ...interface{}) *RareTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.IncludeValues = append(a.includeExclude.IncludeValues, values...) + return a +} + +func (a *RareTermsAggregation) Exclude(regexp string) *RareTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.Exclude = regexp + return a +} + +func (a *RareTermsAggregation) ExcludeValues(values ...interface{}) *RareTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.ExcludeValues = append(a.includeExclude.ExcludeValues, values...) + return a +} + +func (a *RareTermsAggregation) IncludeExclude(includeExclude *TermsAggregationIncludeExclude) *RareTermsAggregation { + a.includeExclude = includeExclude + return a +} + +func (a *RareTermsAggregation) Source() (interface{}, error) { + // Example: + // { + // "aggregations" : { + // "genres" : { + // "rare_terms" : { "field" : "genre" } + // } + // } + // } + // + // This method returns only the + // "rare_terms" : { "field" : "genre" } + // part. + + source := make(map[string]interface{}) + opts := make(map[string]interface{}) + source["rare_terms"] = opts + + if a.field != "" { + opts["field"] = a.field + } + if a.maxDocCount != nil { + opts["max_doc_count"] = *a.maxDocCount + } + if a.precision != nil { + opts["precision"] = *a.precision + } + if a.missing != nil { + opts["missing"] = a.missing + } + + // Include/Exclude + if ie := a.includeExclude; ie != nil { + if err := ie.MergeInto(opts); err != nil { + return nil, err + } + } + + // 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.v6/search_aggs_bucket_reverse_nested.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_reverse_nested.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_reverse_nested.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_reverse_nested.go index b769a53..8f454f8 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_reverse_nested.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-reverse-nested-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-reverse-nested-aggregation.html type ReverseNestedAggregation struct { path string subAggregations map[string]Aggregation diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_sampler.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_sampler.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_sampler.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_sampler.go index 90a879f..d64e6b3 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_sampler.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-bucket-sampler-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.v6/search_aggs_bucket_significant_terms.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_terms.go similarity index 80% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_significant_terms.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_terms.go index 0b8e862..e30cb22 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_significant_terms.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_terms.go @@ -6,7 +6,7 @@ package elastic // SignificantTermsAggregation is an aggregation that returns interesting // or unusual occurrences of terms in a set. -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-significantterms-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html type SignificantTermsAggregation struct { field string subAggregations map[string]Aggregation @@ -19,11 +19,12 @@ type SignificantTermsAggregation struct { filter Query executionHint string significanceHeuristic SignificanceHeuristic + includeExclude *TermsAggregationIncludeExclude } func NewSignificantTermsAggregation() *SignificantTermsAggregation { return &SignificantTermsAggregation{ - subAggregations: make(map[string]Aggregation, 0), + subAggregations: make(map[string]Aggregation), } } @@ -78,6 +79,59 @@ func (a *SignificantTermsAggregation) SignificanceHeuristic(heuristic Significan return a } +func (a *SignificantTermsAggregation) Include(regexp string) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.Include = regexp + return a +} + +func (a *SignificantTermsAggregation) IncludeValues(values ...interface{}) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.IncludeValues = append(a.includeExclude.IncludeValues, values...) + return a +} + +func (a *SignificantTermsAggregation) Exclude(regexp string) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.Exclude = regexp + return a +} + +func (a *SignificantTermsAggregation) ExcludeValues(values ...interface{}) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.ExcludeValues = append(a.includeExclude.ExcludeValues, values...) + return a +} + +func (a *SignificantTermsAggregation) Partition(p int) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.Partition = p + return a +} + +func (a *SignificantTermsAggregation) NumPartitions(n int) *SignificantTermsAggregation { + if a.includeExclude == nil { + a.includeExclude = &TermsAggregationIncludeExclude{} + } + a.includeExclude.NumPartitions = n + return a +} + +func (a *SignificantTermsAggregation) IncludeExclude(includeExclude *TermsAggregationIncludeExclude) *SignificantTermsAggregation { + a.includeExclude = includeExclude + return a +} + func (a *SignificantTermsAggregation) Source() (interface{}, error) { // Example: // { @@ -133,6 +187,13 @@ func (a *SignificantTermsAggregation) Source() (interface{}, error) { opts[name] = src } + // Include/Exclude + if ie := a.includeExclude; ie != nil { + if err := ie.MergeInto(opts); err != nil { + return nil, err + } + } + // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { aggsMap := make(map[string]interface{}) @@ -166,7 +227,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.2/search-aggregations-bucket-significantterms-aggregation.html#_chi_square +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_chi_square // for details. type ChiSquareSignificanceHeuristic struct { backgroundIsSuperset *bool @@ -216,7 +277,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.2/search-aggregations-bucket-significantterms-aggregation.html#_google_normalized_distance +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_google_normalized_distance // for details. type GNDSignificanceHeuristic struct { backgroundIsSuperset *bool @@ -252,7 +313,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.2/search-aggregations-bucket-significantterms-aggregation.html#_jlh_score. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_jlh_score. type JLHScoreSignificanceHeuristic struct{} // NewJLHScoreSignificanceHeuristic initializes a new JLHScoreSignificanceHeuristic. @@ -276,7 +337,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.2/search-aggregations-bucket-significantterms-aggregation.html#_mutual_information +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_mutual_information // for details. type MutualInformationSignificanceHeuristic struct { backgroundIsSuperset *bool @@ -324,7 +385,7 @@ func (sh *MutualInformationSignificanceHeuristic) Source() (interface{}, error) // -- Percentage Score -- // PercentageScoreSignificanceHeuristic implements the algorithm described -// in https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-significantterms-aggregation.html#_percentage. +// in https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_percentage. type PercentageScoreSignificanceHeuristic struct{} // NewPercentageScoreSignificanceHeuristic initializes a new instance of @@ -347,7 +408,7 @@ func (sh *PercentageScoreSignificanceHeuristic) Source() (interface{}, error) { // -- Script -- // ScriptSignificanceHeuristic implements a scripted significance heuristic. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-significantterms-aggregation.html#_scripted +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html#_scripted // for details. type ScriptSignificanceHeuristic struct { script *Script @@ -368,7 +429,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.2/search-aggregations-bucket-significantterms-aggregation.html#_scripted +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.v6/search_aggs_bucket_significant_text.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_text.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_significant_text.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_text.go index df41390..2602df9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_significant_text.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_text.go @@ -6,7 +6,7 @@ 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.2/search-aggregations-bucket-significanttext-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-significanttext-aggregation.html type SignificantTextAggregation struct { field string subAggregations map[string]Aggregation @@ -22,7 +22,7 @@ type SignificantTextAggregation struct { func NewSignificantTextAggregation() *SignificantTextAggregation { return &SignificantTextAggregation{ - subAggregations: make(map[string]Aggregation, 0), + subAggregations: make(map[string]Aggregation), } } @@ -142,6 +142,11 @@ func (a *SignificantTextAggregation) NumPartitions(n int) *SignificantTextAggreg return a } +func (a *SignificantTextAggregation) IncludeExclude(includeExclude *TermsAggregationIncludeExclude) *SignificantTextAggregation { + a.includeExclude = includeExclude + return a +} + func (a *SignificantTextAggregation) Source() (interface{}, error) { // Example: // { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_terms.go b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_terms.go similarity index 82% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_terms.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_bucket_terms.go index 6f66d5f..8f047be 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_bucket_terms.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_bucket_terms.go @@ -4,10 +4,12 @@ package elastic +import "fmt" + // TermsAggregation is a multi-bucket value source based aggregation // where buckets are dynamically built - one per unique value. // -// See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/6.2/search-aggregations-bucket-terms-aggregation.html +// See: http://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-bucket-terms-aggregation.html type TermsAggregation struct { field string script *Script @@ -30,7 +32,7 @@ type TermsAggregation struct { func NewTermsAggregation() *TermsAggregation { return &TermsAggregation{ - subAggregations: make(map[string]Aggregation, 0), + subAggregations: make(map[string]Aggregation), } } @@ -134,6 +136,11 @@ func (a *TermsAggregation) NumPartitions(n int) *TermsAggregation { return a } +func (a *TermsAggregation) IncludeExclude(includeExclude *TermsAggregationIncludeExclude) *TermsAggregation { + a.includeExclude = includeExclude + return a +} + // ValueType can be string, long, or double. func (a *TermsAggregation) ValueType(valueType string) *TermsAggregation { a.valueType = valueType @@ -159,20 +166,37 @@ func (a *TermsAggregation) OrderByCountDesc() *TermsAggregation { return a.OrderByCount(false) } +// Deprecated: Use OrderByKey instead. func (a *TermsAggregation) OrderByTerm(asc bool) *TermsAggregation { // "order" : { "_term" : "asc" } a.order = append(a.order, TermsOrder{Field: "_term", Ascending: asc}) return a } +// Deprecated: Use OrderByKeyAsc instead. func (a *TermsAggregation) OrderByTermAsc() *TermsAggregation { return a.OrderByTerm(true) } +// Deprecated: Use OrderByKeyDesc instead. func (a *TermsAggregation) OrderByTermDesc() *TermsAggregation { return a.OrderByTerm(false) } +func (a *TermsAggregation) OrderByKey(asc bool) *TermsAggregation { + // "order" : { "_term" : "asc" } + a.order = append(a.order, TermsOrder{Field: "_key", Ascending: asc}) + return a +} + +func (a *TermsAggregation) OrderByKeyAsc() *TermsAggregation { + return a.OrderByKey(true) +} + +func (a *TermsAggregation) OrderByKeyDesc() *TermsAggregation { + return a.OrderByKey(false) +} + // OrderByAggregation creates a bucket ordering strategy which sorts buckets // based on a single-valued calc get. func (a *TermsAggregation) OrderByAggregation(aggName string, asc bool) *TermsAggregation { @@ -295,24 +319,11 @@ func (a *TermsAggregation) Source() (interface{}, error) { } opts["order"] = orderSlice } + // 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 + if err := ie.MergeInto(opts); err != nil { + return nil, err } } @@ -351,6 +362,48 @@ type TermsAggregationIncludeExclude struct { NumPartitions int } +// Source returns a JSON serializable struct. +func (ie *TermsAggregationIncludeExclude) Source() (interface{}, error) { + source := make(map[string]interface{}) + + // Include + if ie.Include != "" { + source["include"] = ie.Include + } else if len(ie.IncludeValues) > 0 { + source["include"] = ie.IncludeValues + } else if ie.NumPartitions > 0 { + inc := make(map[string]interface{}) + inc["partition"] = ie.Partition + inc["num_partitions"] = ie.NumPartitions + source["include"] = inc + } + + // Exclude + if ie.Exclude != "" { + source["exclude"] = ie.Exclude + } else if len(ie.ExcludeValues) > 0 { + source["exclude"] = ie.ExcludeValues + } + + return source, nil +} + +// MergeInto merges the values of the include/exclude options into source. +func (ie *TermsAggregationIncludeExclude) MergeInto(source map[string]interface{}) error { + values, err := ie.Source() + if err != nil { + return err + } + mv, ok := values.(map[string]interface{}) + if !ok { + return fmt.Errorf("IncludeExclude: expected a map[string]interface{}, got %T", values) + } + for k, v := range mv { + source[k] = v + } + return nil +} + // TermsOrder specifies a single order field for a terms aggregation. type TermsOrder struct { Field string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_matrix_stats.go b/vendor/github.com/olivere/elastic/v7/search_aggs_matrix_stats.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_matrix_stats.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_matrix_stats.go index fe96d1e..f0eb457 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_matrix_stats.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_matrix_stats.go @@ -11,7 +11,7 @@ package elastic // // The stats that are returned consist of: min, max, sum, count and avg. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-stats-aggregation.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-stats-aggregation.html // for details. type MatrixStatsAggregation struct { fields []string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_avg.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_avg.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_avg.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_avg.go index 6fd9420..7f58caf 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_avg.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_avg.go @@ -10,11 +10,12 @@ package elastic // specific numeric fields in the documents, or be generated by // a provided script. // -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-avg-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-avg-aggregation.html type AvgAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} } @@ -40,6 +41,11 @@ func (a *AvgAggregation) Format(format string) *AvgAggregation { return a } +func (a *AvgAggregation) Missing(missing interface{}) *AvgAggregation { + a.missing = missing + return a +} + func (a *AvgAggregation) SubAggregation(name string, subAggregation Aggregation) *AvgAggregation { a.subAggregations[name] = subAggregation return a @@ -80,6 +86,10 @@ func (a *AvgAggregation) Source() (interface{}, error) { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } + // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { aggsMap := make(map[string]interface{}) diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_cardinality.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_cardinality.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_cardinality.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_cardinality.go index e50d786..f0599a6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_cardinality.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_cardinality.go @@ -8,11 +8,12 @@ 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.2/search-aggregations-metrics-cardinality-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-cardinality-aggregation.html type CardinalityAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} precisionThreshold *int64 @@ -40,6 +41,10 @@ func (a *CardinalityAggregation) Format(format string) *CardinalityAggregation { return a } +func (a *CardinalityAggregation) Missing(missing interface{}) *CardinalityAggregation { + a.missing = missing + return a +} func (a *CardinalityAggregation) SubAggregation(name string, subAggregation Aggregation) *CardinalityAggregation { a.subAggregations[name] = subAggregation return a @@ -87,7 +92,9 @@ func (a *CardinalityAggregation) Source() (interface{}, error) { } opts["script"] = src } - + if a.missing != nil { + opts["missing"] = a.missing + } if a.format != "" { opts["format"] = a.format } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_extended_stats.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_extended_stats.go similarity index 85% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_extended_stats.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_extended_stats.go index 425444d..3008a8d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_extended_stats.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_extended_stats.go @@ -8,11 +8,13 @@ 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.2/search-aggregations-metrics-extendedstats-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-extendedstats-aggregation.html type ExtendedStatsAggregation struct { field string script *Script format string + missing interface{} + sigma *float64 subAggregations map[string]Aggregation meta map[string]interface{} } @@ -38,6 +40,16 @@ func (a *ExtendedStatsAggregation) Format(format string) *ExtendedStatsAggregati return a } +func (a *ExtendedStatsAggregation) Missing(missing interface{}) *ExtendedStatsAggregation { + a.missing = missing + return a +} + +func (a *ExtendedStatsAggregation) Sigma(sigma float64) *ExtendedStatsAggregation { + a.sigma = &sigma + return a +} + func (a *ExtendedStatsAggregation) SubAggregation(name string, subAggregation Aggregation) *ExtendedStatsAggregation { a.subAggregations[name] = subAggregation return a @@ -76,6 +88,12 @@ func (a *ExtendedStatsAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if v := a.missing; v != nil { + opts["missing"] = v + } + if v := a.sigma; v != nil { + opts["sigma"] = *v + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_bounds.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_bounds.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_bounds.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_bounds.go index 3a322ed..007e302 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_bounds.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-metrics-geobounds-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-geobounds-aggregation.html type GeoBoundsAggregation struct { field string script *Script diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_centroid.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_centroid.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_centroid.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_centroid.go index 23a0f78..55b3f48 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_geo_centroid.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_centroid.go @@ -6,7 +6,7 @@ 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/6.2/search-aggregations-metrics-geocentroid-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-geocentroid-aggregation.html type GeoCentroidAggregation struct { field string script *Script diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_max.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_max.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_max.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_max.go index 7d2c39f..9128a25 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_max.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_max.go @@ -9,11 +9,12 @@ 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.2/search-aggregations-metrics-max-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-max-aggregation.html type MaxAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} } @@ -39,6 +40,11 @@ func (a *MaxAggregation) Format(format string) *MaxAggregation { return a } +func (a *MaxAggregation) Missing(missing interface{}) *MaxAggregation { + a.missing = missing + return a +} + func (a *MaxAggregation) SubAggregation(name string, subAggregation Aggregation) *MaxAggregation { a.subAggregations[name] = subAggregation return a @@ -76,6 +82,9 @@ func (a *MaxAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_median_absolute_deviation.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_median_absolute_deviation.go new file mode 100644 index 0000000..dcf4213 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_median_absolute_deviation.go @@ -0,0 +1,119 @@ +// 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 + +// MedianAbsoluteDeviationAggregation is a measure of variability. +// It is a robust statistic, meaning that it is useful for describing data +// that may have outliers, or may not be normally distributed. +// For such data it can be more descriptive than standard deviation. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.6/search-aggregations-metrics-median-absolute-deviation-aggregation.html +// for details. +type MedianAbsoluteDeviationAggregation struct { + field string + compression *float64 + script *Script + format string + missing interface{} + subAggregations map[string]Aggregation + meta map[string]interface{} +} + +func NewMedianAbsoluteDeviationAggregation() *MedianAbsoluteDeviationAggregation { + return &MedianAbsoluteDeviationAggregation{ + subAggregations: make(map[string]Aggregation), + } +} + +func (a *MedianAbsoluteDeviationAggregation) Field(field string) *MedianAbsoluteDeviationAggregation { + a.field = field + return a +} + +func (a *MedianAbsoluteDeviationAggregation) Compression(compression float64) *MedianAbsoluteDeviationAggregation { + a.compression = &compression + return a +} + +func (a *MedianAbsoluteDeviationAggregation) Script(script *Script) *MedianAbsoluteDeviationAggregation { + a.script = script + return a +} + +func (a *MedianAbsoluteDeviationAggregation) Format(format string) *MedianAbsoluteDeviationAggregation { + a.format = format + return a +} + +func (a *MedianAbsoluteDeviationAggregation) Missing(missing interface{}) *MedianAbsoluteDeviationAggregation { + a.missing = missing + return a +} + +func (a *MedianAbsoluteDeviationAggregation) SubAggregation(name string, subAggregation Aggregation) *MedianAbsoluteDeviationAggregation { + a.subAggregations[name] = subAggregation + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *MedianAbsoluteDeviationAggregation) Meta(metaData map[string]interface{}) *MedianAbsoluteDeviationAggregation { + a.meta = metaData + return a +} + +func (a *MedianAbsoluteDeviationAggregation) Source() (interface{}, error) { + // Example: + // { + // "aggs" : { + // "review_variability" : { "median_absolute_deviation" : { "field" : "rating" } } + // } + // } + // This method returns only the { "median_absolute_deviation" : { "field" : "rating" } } part. + + source := make(map[string]interface{}) + opts := make(map[string]interface{}) + source["median_absolute_deviation"] = opts + + // ValuesSourceAggregationBuilder + if a.field != "" { + opts["field"] = a.field + } + if v := a.compression; v != nil { + opts["compression"] = *v + } + if a.script != nil { + src, err := a.script.Source() + if err != nil { + return nil, err + } + opts["script"] = src + } + if a.format != "" { + opts["format"] = a.format + } + if a.missing != nil { + opts["missing"] = a.missing + } + + // 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.v6/search_aggs_metrics_min.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_min.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_min.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_min.go index 8c963d1..b6e40f9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_min.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_min.go @@ -9,11 +9,12 @@ 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.2/search-aggregations-metrics-min-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-min-aggregation.html type MinAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} } @@ -39,6 +40,11 @@ func (a *MinAggregation) Format(format string) *MinAggregation { return a } +func (a *MinAggregation) Missing(missing interface{}) *MinAggregation { + a.missing = missing + return a +} + func (a *MinAggregation) SubAggregation(name string, subAggregation Aggregation) *MinAggregation { a.subAggregations[name] = subAggregation return a @@ -77,6 +83,9 @@ func (a *MinAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentile_ranks.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentile_ranks.go similarity index 92% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentile_ranks.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentile_ranks.go index 684ffc8..a62ff4c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentile_ranks.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentile_ranks.go @@ -5,11 +5,12 @@ package elastic // PercentileRanksAggregation -// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-metrics-percentile-rank-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-percentile-rank-aggregation.html type PercentileRanksAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} values []float64 @@ -39,6 +40,11 @@ func (a *PercentileRanksAggregation) Format(format string) *PercentileRanksAggre return a } +func (a *PercentileRanksAggregation) Missing(missing interface{}) *PercentileRanksAggregation { + a.missing = missing + return a +} + func (a *PercentileRanksAggregation) SubAggregation(name string, subAggregation Aggregation) *PercentileRanksAggregation { a.subAggregations[name] = subAggregation return a @@ -99,6 +105,9 @@ func (a *PercentileRanksAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } if len(a.values) > 0 { opts["values"] = a.values } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentiles.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentiles.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentiles.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentiles.go index 1be079f..1eb62de 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_percentiles.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentiles.go @@ -10,22 +10,26 @@ package elastic // 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.2/search-aggregations-metrics-percentile-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-percentile-aggregation.html type PercentilesAggregation struct { - field string - script *Script - format string - subAggregations map[string]Aggregation - meta map[string]interface{} - percentiles []float64 - compression *float64 - estimator string + field string + script *Script + format string + missing interface{} + subAggregations map[string]Aggregation + meta map[string]interface{} + percentiles []float64 + method string + compression *float64 + numberOfSignificantValueDigits *int + estimator string } func NewPercentilesAggregation() *PercentilesAggregation { return &PercentilesAggregation{ subAggregations: make(map[string]Aggregation), percentiles: make([]float64, 0), + method: "tdigest", } } @@ -44,6 +48,11 @@ func (a *PercentilesAggregation) Format(format string) *PercentilesAggregation { return a } +func (a *PercentilesAggregation) Missing(missing interface{}) *PercentilesAggregation { + a.missing = missing + return a +} + func (a *PercentilesAggregation) SubAggregation(name string, subAggregation Aggregation) *PercentilesAggregation { a.subAggregations[name] = subAggregation return a @@ -60,11 +69,22 @@ func (a *PercentilesAggregation) Percentiles(percentiles ...float64) *Percentile return a } +// Method is the percentiles method, which can be "tdigest" (default) or "hdr". +func (a *PercentilesAggregation) Method(method string) *PercentilesAggregation { + a.method = method + return a +} + func (a *PercentilesAggregation) Compression(compression float64) *PercentilesAggregation { a.compression = &compression return a } +func (a *PercentilesAggregation) NumberOfSignificantValueDigits(digits int) *PercentilesAggregation { + a.numberOfSignificantValueDigits = &digits + return a +} + func (a *PercentilesAggregation) Estimator(estimator string) *PercentilesAggregation { a.estimator = estimator return a @@ -103,11 +123,25 @@ func (a *PercentilesAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } if len(a.percentiles) > 0 { opts["percents"] = a.percentiles } - if a.compression != nil { - opts["compression"] = *a.compression + switch a.method { + case "tdigest": + if c := a.compression; c != nil { + opts[a.method] = map[string]interface{}{ + "compression": *c, + } + } + case "hdr": + if n := a.numberOfSignificantValueDigits; n != nil { + opts[a.method] = map[string]interface{}{ + "number_of_significant_value_digits": *n, + } + } } if a.estimator != "" { opts["estimator"] = a.estimator diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_scripted_metric.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_scripted_metric.go new file mode 100644 index 0000000..0b26c9d --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_scripted_metric.go @@ -0,0 +1,112 @@ +// 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 + +// ScriptedMetricAggregation is a a metric aggregation that executes using scripts to provide a metric output. +// +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-scripted-metric-aggregation.html +type ScriptedMetricAggregation struct { + initScript *Script + mapScript *Script + combineScript *Script + reduceScript *Script + + params map[string]interface{} + meta map[string]interface{} +} + +func NewScriptedMetricAggregation() *ScriptedMetricAggregation { + a := &ScriptedMetricAggregation{} + return a +} + +func (a *ScriptedMetricAggregation) InitScript(script *Script) *ScriptedMetricAggregation { + a.initScript = script + return a +} + +func (a *ScriptedMetricAggregation) MapScript(script *Script) *ScriptedMetricAggregation { + a.mapScript = script + return a +} + +func (a *ScriptedMetricAggregation) CombineScript(script *Script) *ScriptedMetricAggregation { + a.combineScript = script + return a +} + +func (a *ScriptedMetricAggregation) ReduceScript(script *Script) *ScriptedMetricAggregation { + a.reduceScript = script + return a +} + +func (a *ScriptedMetricAggregation) Params(params map[string]interface{}) *ScriptedMetricAggregation { + a.params = params + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *ScriptedMetricAggregation) Meta(metaData map[string]interface{}) *ScriptedMetricAggregation { + a.meta = metaData + return a +} + +func (a *ScriptedMetricAggregation) Source() (interface{}, error) { + // Example: + // { + // "aggs" : { + // "magic_script" : { "scripted_metric" : { + // "init_script" : "state.transactions = []", + // "map_script" : "state.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)", + // "combine_script" : "double profit = 0; for (t in state.transactions) { profit += t } return profit", + // "reduce_script" : "double profit = 0; for (a in states) { profit += a } return profit" + // } } + // } + // } + // This method returns only the { "scripted_metric" : { ... } } part. + + source := make(map[string]interface{}) + opts := make(map[string]interface{}) + source["scripted_metric"] = opts + + if a.initScript != nil { + src, err := a.initScript.Source() + if err != nil { + return nil, err + } + opts["init_script"] = src + } + if a.mapScript != nil { + src, err := a.mapScript.Source() + if err != nil { + return nil, err + } + opts["map_script"] = src + } + if a.combineScript != nil { + src, err := a.combineScript.Source() + if err != nil { + return nil, err + } + opts["combine_script"] = src + } + if a.reduceScript != nil { + src, err := a.reduceScript.Source() + if err != nil { + return nil, err + } + opts["reduce_script"] = src + } + + if a.params != nil && len(a.params) > 0 { + opts["params"] = a.params + } + + // 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.v6/search_aggs_metrics_stats.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_stats.go similarity index 90% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_stats.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_stats.go index f193409..6c00f68 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_stats.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_stats.go @@ -8,11 +8,12 @@ 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.2/search-aggregations-metrics-stats-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-stats-aggregation.html type StatsAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} } @@ -38,6 +39,11 @@ func (a *StatsAggregation) Format(format string) *StatsAggregation { return a } +func (a *StatsAggregation) Missing(missing interface{}) *StatsAggregation { + a.missing = missing + return a +} + func (a *StatsAggregation) SubAggregation(name string, subAggregation Aggregation) *StatsAggregation { a.subAggregations[name] = subAggregation return a @@ -76,6 +82,9 @@ func (a *StatsAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_sum.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_sum.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_sum.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_sum.go index ebef150..6de8f1d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_sum.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_sum.go @@ -8,11 +8,12 @@ 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.2/search-aggregations-metrics-sum-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-sum-aggregation.html type SumAggregation struct { field string script *Script format string + missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} } @@ -38,6 +39,11 @@ func (a *SumAggregation) Format(format string) *SumAggregation { return a } +func (a *SumAggregation) Missing(missing interface{}) *SumAggregation { + a.missing = missing + return a +} + func (a *SumAggregation) SubAggregation(name string, subAggregation Aggregation) *SumAggregation { a.subAggregations[name] = subAggregation return a @@ -76,6 +82,9 @@ func (a *SumAggregation) Source() (interface{}, error) { if a.format != "" { opts["format"] = a.format } + if a.missing != nil { + opts["missing"] = a.missing + } // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_top_hits.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_top_hits.go similarity index 86% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_top_hits.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_top_hits.go index a78e556..7321667 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_top_hits.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-metrics-top-hits-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-top-hits-aggregation.html type TopHitsAggregation struct { searchSource *SearchSource } @@ -24,6 +24,14 @@ func NewTopHitsAggregation() *TopHitsAggregation { } } +func (a *TopHitsAggregation) SearchSource(searchSource *SearchSource) *TopHitsAggregation { + a.searchSource = searchSource + if a.searchSource == nil { + a.searchSource = NewSearchSource() + } + return a +} + func (a *TopHitsAggregation) From(from int) *TopHitsAggregation { a.searchSource = a.searchSource.From(from) return a @@ -69,11 +77,21 @@ func (a *TopHitsAggregation) DocvalueFields(docvalueFields ...string) *TopHitsAg return a } +func (a *TopHitsAggregation) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *TopHitsAggregation { + a.searchSource = a.searchSource.DocvalueFieldsWithFormat(docvalueFields...) + return a +} + func (a *TopHitsAggregation) DocvalueField(docvalueField string) *TopHitsAggregation { a.searchSource = a.searchSource.DocvalueField(docvalueField) return a } +func (a *TopHitsAggregation) DocvalueFieldWithFormat(docvalueField DocvalueField) *TopHitsAggregation { + a.searchSource = a.searchSource.DocvalueFieldWithFormat(docvalueField) + return a +} + func (a *TopHitsAggregation) ScriptFields(scriptFields ...*ScriptField) *TopHitsAggregation { a.searchSource = a.searchSource.ScriptFields(scriptFields...) return a diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_value_count.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_value_count.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_value_count.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_metrics_value_count.go index abcc166..b948dcc 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_metrics_value_count.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-metrics-valuecount-aggregation.html +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-valuecount-aggregation.html type ValueCountAggregation struct { field string script *Script diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_weighted_avg.go b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_weighted_avg.go new file mode 100644 index 0000000..cd7ad7e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_metrics_weighted_avg.go @@ -0,0 +1,156 @@ +// 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 + +// WeightedAvgAggregation is a single-value metrics aggregation that +// computes the weighted average of numeric values that are extracted +// from the aggregated documents. These values can be extracted either +// from specific numeric fields in the documents. +// +// See: https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-metrics-weight-avg-aggregation.html +type WeightedAvgAggregation struct { + fields map[string]*MultiValuesSourceFieldConfig + valueType string + format string + value *MultiValuesSourceFieldConfig + weight *MultiValuesSourceFieldConfig + subAggregations map[string]Aggregation + meta map[string]interface{} +} + +func NewWeightedAvgAggregation() *WeightedAvgAggregation { + return &WeightedAvgAggregation{ + fields: make(map[string]*MultiValuesSourceFieldConfig), + subAggregations: make(map[string]Aggregation), + } +} + +func (a *WeightedAvgAggregation) Field(field string, config *MultiValuesSourceFieldConfig) *WeightedAvgAggregation { + a.fields[field] = config + return a +} + +func (a *WeightedAvgAggregation) ValueType(valueType string) *WeightedAvgAggregation { + a.valueType = valueType + return a +} + +func (a *WeightedAvgAggregation) Format(format string) *WeightedAvgAggregation { + a.format = format + return a +} + +func (a *WeightedAvgAggregation) Value(value *MultiValuesSourceFieldConfig) *WeightedAvgAggregation { + a.value = value + return a +} + +func (a *WeightedAvgAggregation) Weight(weight *MultiValuesSourceFieldConfig) *WeightedAvgAggregation { + a.weight = weight + return a +} + +func (a *WeightedAvgAggregation) SubAggregation(name string, subAggregation Aggregation) *WeightedAvgAggregation { + a.subAggregations[name] = subAggregation + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *WeightedAvgAggregation) Meta(metaData map[string]interface{}) *WeightedAvgAggregation { + a.meta = metaData + return a +} + +func (a *WeightedAvgAggregation) Source() (interface{}, error) { + source := make(map[string]interface{}) + opts := make(map[string]interface{}) + source["weighted_avg"] = opts + + if len(a.fields) > 0 { + f := make(map[string]interface{}) + for name, config := range a.fields { + cfg, err := config.Source() + if err != nil { + return nil, err + } + f[name] = cfg + } + opts["fields"] = f + } + + if v := a.format; v != "" { + opts["format"] = v + } + + if v := a.valueType; v != "" { + opts["value_type"] = v + } + + if v := a.value; v != nil { + cfg, err := v.Source() + if err != nil { + return nil, err + } + opts["value"] = cfg + } + + if v := a.weight; v != nil { + cfg, err := v.Source() + if err != nil { + return nil, err + } + opts["weight"] = cfg + } + + // 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 +} + +// MultiValuesSourceFieldConfig represents a field configuration +// used e.g. in WeightedAvgAggregation. +type MultiValuesSourceFieldConfig struct { + FieldName string + Missing interface{} + Script *Script + TimeZone string +} + +func (f *MultiValuesSourceFieldConfig) Source() (interface{}, error) { + source := make(map[string]interface{}) + if v := f.Missing; v != nil { + source["missing"] = v + } + if v := f.Script; v != nil { + src, err := v.Source() + if err != nil { + return nil, err + } + source["script"] = src + } + if v := f.FieldName; v != "" { + source["field"] = v + } + if v := f.TimeZone; v != "" { + source["time_zone"] = v + } + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_avg_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_avg_bucket.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_avg_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_avg_bucket.go index 97046fd..5c130d6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_avg_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-avg-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-avg-bucket-aggregation.html type AvgBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_script.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_script.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_script.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_script.go index 4646ab5..bc5229b 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_script.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-bucket-script-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-bucket-script-aggregation.html type BucketScriptAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_selector.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_selector.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_selector.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_selector.go index 2ad6d41..1051f1a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_selector.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-bucket-selector-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-bucket-selector-aggregation.html type BucketSelectorAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_sort.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_sort.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_sort.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_sort.go index cd3075f..3d060df 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_bucket_sort.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_sort.go @@ -11,7 +11,7 @@ package elastic // parameters from and size may be set in order to truncate the result buckets. // // For more details, see -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-bucket-sort-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-bucket-sort-aggregation.html type BucketSortAggregation struct { sorters []Sorter from int diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_cumulative_sum.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_cumulative_sum.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_cumulative_sum.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_cumulative_sum.go index 18cb5e8..1074d86 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_cumulative_sum.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-cumulative-sum-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-cumulative-sum-aggregation.html type CumulativeSumAggregation struct { format string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_derivative.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_derivative.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_derivative.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_derivative.go index 706be7c..a22219c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_derivative.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-derivative-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-derivative-aggregation.html type DerivativeAggregation struct { format string gapPolicy string diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_extended_stats_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_extended_stats_bucket.go new file mode 100644 index 0000000..4e816d4 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_extended_stats_bucket.go @@ -0,0 +1,107 @@ +// 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 + +// ExtendedStatsBucketAggregation is a sibling pipeline aggregation which calculates +// a variety of stats across all bucket of a specified metric in a sibling aggregation. +// The specified metric must be numeric and the sibling aggregation must +// be a multi-bucket aggregation. +// +// This aggregation provides a few more statistics (sum of squares, standard deviation, etc) +// compared to the stats_bucket aggregation. +// For more details, see +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-extended-stats-bucket-aggregation.html +type ExtendedStatsBucketAggregation struct { + format string + gapPolicy string + sigma *float32 + meta map[string]interface{} + bucketsPaths []string +} + +// NewExtendedStatsBucketAggregation creates and initializes a new ExtendedStatsBucketAggregation. +func NewExtendedStatsBucketAggregation() *ExtendedStatsBucketAggregation { + return &ExtendedStatsBucketAggregation{ + bucketsPaths: make([]string, 0), + } +} + +// Format to use on the output of this aggregation. +func (s *ExtendedStatsBucketAggregation) Format(format string) *ExtendedStatsBucketAggregation { + s.format = format + return s +} + +// GapPolicy defines what should be done when a gap in the series is discovered. +// Valid values include "insert_zeros" or "skip". Default is "insert_zeros". +func (s *ExtendedStatsBucketAggregation) GapPolicy(gapPolicy string) *ExtendedStatsBucketAggregation { + s.gapPolicy = gapPolicy + return s +} + +// GapInsertZeros inserts zeros for gaps in the series. +func (s *ExtendedStatsBucketAggregation) GapInsertZeros() *ExtendedStatsBucketAggregation { + s.gapPolicy = "insert_zeros" + return s +} + +// GapSkip skips gaps in the series. +func (s *ExtendedStatsBucketAggregation) GapSkip() *ExtendedStatsBucketAggregation { + s.gapPolicy = "skip" + return s +} + +// Meta sets the meta data to be included in the aggregation response. +func (s *ExtendedStatsBucketAggregation) Meta(metaData map[string]interface{}) *ExtendedStatsBucketAggregation { + s.meta = metaData + return s +} + +// BucketsPath sets the paths to the buckets to use for this pipeline aggregator. +func (s *ExtendedStatsBucketAggregation) BucketsPath(bucketsPaths ...string) *ExtendedStatsBucketAggregation { + s.bucketsPaths = append(s.bucketsPaths, bucketsPaths...) + return s +} + +// Sigma sets number of standard deviations above/below the mean to display +func (s *ExtendedStatsBucketAggregation) Sigma(sigma float32) *ExtendedStatsBucketAggregation { + s.sigma = &sigma + return s +} + +// Source returns the a JSON-serializable interface. +func (s *ExtendedStatsBucketAggregation) Source() (interface{}, error) { + source := make(map[string]interface{}) + params := make(map[string]interface{}) + source["extended_stats_bucket"] = params + + if s.format != "" { + params["format"] = s.format + } + if s.gapPolicy != "" { + params["gap_policy"] = s.gapPolicy + } + + // Add buckets paths + switch len(s.bucketsPaths) { + case 0: + case 1: + params["buckets_path"] = s.bucketsPaths[0] + default: + params["buckets_path"] = s.bucketsPaths + } + + // Add sigma is not zero or less + if s.sigma != nil && *s.sigma >= 0 { + params["sigma"] = *s.sigma + } + + // Add Meta data if available + if len(s.meta) > 0 { + source["meta"] = s.meta + } + + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_max_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_max_bucket.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_max_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_max_bucket.go index 42aad23..6cd087e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_max_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-max-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-max-bucket-aggregation.html type MaxBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_min_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_min_bucket.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_min_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_min_bucket.go index 1a3d3d8..c87f0d9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_min_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-min-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-min-bucket-aggregation.html type MinBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_mov_avg.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_avg.go similarity index 93% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_mov_avg.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_avg.go index f380812..035dc0e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_mov_avg.go +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_avg.go @@ -8,7 +8,9 @@ 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.2/search-aggregations-pipeline-movavg-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html +// +// Deprecated: The MovAvgAggregation has been deprecated in 6.4.0. Use the more generate MovFnAggregation instead. type MovAvgAggregation struct { format string gapPolicy string @@ -22,6 +24,8 @@ type MovAvgAggregation struct { } // NewMovAvgAggregation creates and initializes a new MovAvgAggregation. +// +// Deprecated: The MovAvgAggregation has been deprecated in 6.4.0. Use the more generate MovFnAggregation instead. func NewMovAvgAggregation() *MovAvgAggregation { return &MovAvgAggregation{ bucketsPaths: make([]string, 0), @@ -143,7 +147,7 @@ func (a *MovAvgAggregation) Source() (interface{}, error) { } // -- Models for moving averages -- -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-movavg-aggregation.html#_models +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_models // MovAvgModel specifies the model to use with the MovAvgAggregation. type MovAvgModel interface { @@ -156,7 +160,7 @@ type MovAvgModel interface { // EWMAMovAvgModel calculates an exponentially weighted moving average. // // For more details, see -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-aggregations-pipeline-movavg-aggregation.html#_ewma_exponentially_weighted +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_ewma_exponentially_weighted type EWMAMovAvgModel struct { alpha *float64 } @@ -194,7 +198,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.2/search-aggregations-pipeline-movavg-aggregation.html#_holt_linear +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_holt_linear type HoltLinearMovAvgModel struct { alpha *float64 beta *float64 @@ -243,7 +247,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.2/search-aggregations-pipeline-movavg-aggregation.html#_holt_winters +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_holt_winters type HoltWintersMovAvgModel struct { alpha *float64 beta *float64 @@ -330,7 +334,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.2/search-aggregations-pipeline-movavg-aggregation.html#_linear +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_linear type LinearMovAvgModel struct { } @@ -354,7 +358,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.2/search-aggregations-pipeline-movavg-aggregation.html#_simple +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html#_simple type SimpleMovAvgModel struct { } diff --git a/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_fn.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_fn.go new file mode 100644 index 0000000..ea8cbdc --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_fn.go @@ -0,0 +1,132 @@ +// 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 + +// MovFnAggregation, given an ordered series of data, will slice a window across +// the data and allow the user to specify a custom script that is executed for +// each window of data. +// +// You must pass a script to process the values. There are a number of predefined +// script functions you can use as described here: +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movfn-aggregation.html#_pre_built_functions. +// +// Example: +// agg := elastic.NewMovFnAggregation( +// "the_sum", // bucket path +// elastic.NewScript("MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"), +// 10, // window size +// ) +// +// For more details, see +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-movfn-aggregation.html. +type MovFnAggregation struct { + script *Script + format string + gapPolicy string + window int + + meta map[string]interface{} + bucketsPaths []string +} + +// NewMovFnAggregation creates and initializes a new MovFnAggregation. +// +// Deprecated: The MovFnAggregation has been deprecated in 6.4.0. Use the more generate MovFnAggregation instead. +func NewMovFnAggregation(bucketsPath string, script *Script, window int) *MovFnAggregation { + return &MovFnAggregation{ + bucketsPaths: []string{bucketsPath}, + script: script, + window: window, + } +} + +// Script is the script to run. +func (a *MovFnAggregation) Script(script *Script) *MovFnAggregation { + a.script = script + return a +} + +// Format to use on the output of this aggregation. +func (a *MovFnAggregation) Format(format string) *MovFnAggregation { + a.format = format + return a +} + +// GapPolicy defines what should be done when a gap in the series is discovered. +// Valid values include "insert_zeros" or "skip". Default is "insert_zeros". +func (a *MovFnAggregation) GapPolicy(gapPolicy string) *MovFnAggregation { + a.gapPolicy = gapPolicy + return a +} + +// GapInsertZeros inserts zeros for gaps in the series. +func (a *MovFnAggregation) GapInsertZeros() *MovFnAggregation { + a.gapPolicy = "insert_zeros" + return a +} + +// GapSkip skips gaps in the series. +func (a *MovFnAggregation) GapSkip() *MovFnAggregation { + a.gapPolicy = "skip" + return a +} + +// Window sets the window size for this aggregation. +func (a *MovFnAggregation) Window(window int) *MovFnAggregation { + a.window = window + return a +} + +// Meta sets the meta data to be included in the aggregation response. +func (a *MovFnAggregation) Meta(metaData map[string]interface{}) *MovFnAggregation { + a.meta = metaData + return a +} + +// BucketsPath sets the paths to the buckets to use for this pipeline aggregator. +func (a *MovFnAggregation) BucketsPath(bucketsPaths ...string) *MovFnAggregation { + a.bucketsPaths = append(a.bucketsPaths, bucketsPaths...) + return a +} + +// Source returns the a JSON-serializable interface. +func (a *MovFnAggregation) Source() (interface{}, error) { + source := make(map[string]interface{}) + params := make(map[string]interface{}) + source["moving_fn"] = params + + // Add buckets paths + switch len(a.bucketsPaths) { + case 0: + case 1: + params["buckets_path"] = a.bucketsPaths[0] + default: + params["buckets_path"] = a.bucketsPaths + } + + // Script + if a.script != nil { + src, err := a.script.Source() + if err != nil { + return nil, err + } + params["script"] = src + } + + if a.format != "" { + params["format"] = a.format + } + if a.gapPolicy != "" { + params["gap_policy"] = a.gapPolicy + } + params["window"] = a.window + + // Add Meta data if available + if len(a.meta) > 0 { + source["meta"] = a.meta + } + + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_percentiles_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_percentiles_bucket.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_percentiles_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_percentiles_bucket.go index 671e31e..a5a3fdf 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_percentiles_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-percentiles-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-percentiles-bucket-aggregation.html type PercentilesBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_serial_diff.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_serial_diff.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_serial_diff.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_serial_diff.go index 98f84b5..d2a9b4c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_serial_diff.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-serialdiff-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-serialdiff-aggregation.html type SerialDiffAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_stats_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_stats_bucket.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_stats_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_stats_bucket.go index 3f3682e..2eb61eb 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_stats_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-stats-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-stats-bucket-aggregation.html type StatsBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_sum_bucket.go b/vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_sum_bucket.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_sum_bucket.go rename to vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_sum_bucket.go index a623ef3..cfdafce 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_aggs_pipeline_sum_bucket.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-aggregations-pipeline-sum-bucket-aggregation.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-aggregations-pipeline-sum-bucket-aggregation.html type SumBucketAggregation struct { format string gapPolicy string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_collapse_builder.go b/vendor/github.com/olivere/elastic/v7/search_collapse_builder.go similarity index 94% rename from vendor/gopkg.in/olivere/elastic.v6/search_collapse_builder.go rename to vendor/github.com/olivere/elastic/v7/search_collapse_builder.go index c2a214b..0de4eed 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_collapse_builder.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-request-collapse.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-collapse.html // for details. type CollapseBuilder struct { field string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_bool.go b/vendor/github.com/olivere/elastic/v7/search_queries_bool.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_bool.go rename to vendor/github.com/olivere/elastic/v7/search_queries_bool.go index e6b0592..d192d79 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_bool.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-bool-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-bool-query.html type BoolQuery struct { Query mustClauses []Query diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_boosting.go b/vendor/github.com/olivere/elastic/v7/search_queries_boosting.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_boosting.go rename to vendor/github.com/olivere/elastic/v7/search_queries_boosting.go index 303bca0..7a76efb 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_boosting.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-boosting-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-boosting-query.html type BoostingQuery struct { Query positiveClause Query diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_common_terms.go b/vendor/github.com/olivere/elastic/v7/search_queries_common_terms.go similarity index 93% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_common_terms.go rename to vendor/github.com/olivere/elastic/v7/search_queries_common_terms.go index d19360e..a10a213 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_common_terms.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_common_terms.go @@ -8,7 +8,11 @@ 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.2/query-dsl-common-terms-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl-common-terms-query.html +// +// Deprecated: Use Match query instead (7.3.0+), which skips blocks of +// documents efficiently, without any configuration, provided that the +// total number of hits is not tracked. type CommonTermsQuery struct { Query name string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_constant_score.go b/vendor/github.com/olivere/elastic/v7/search_queries_constant_score.go similarity index 95% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_constant_score.go rename to vendor/github.com/olivere/elastic/v7/search_queries_constant_score.go index 088e9b5..cfa8dff 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_constant_score.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-constant-score-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-constant-score-query.html type ConstantScoreQuery struct { filter Query boost *float64 diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_dis_max.go b/vendor/github.com/olivere/elastic/v7/search_queries_dis_max.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_dis_max.go rename to vendor/github.com/olivere/elastic/v7/search_queries_dis_max.go index 8082736..48376d6 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_dis_max.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-dis-max-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-dis-max-query.html type DisMaxQuery struct { queries []Query boost *float64 diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_distance_feature_query.go b/vendor/github.com/olivere/elastic/v7/search_queries_distance_feature_query.go new file mode 100644 index 0000000..1a8a061 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_distance_feature_query.go @@ -0,0 +1,119 @@ +// 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 ( + "fmt" +) + +// DistanceFeatureQuery uses a script to provide a custom score for returned documents. +// +// A DistanceFeatureQuery query is useful if, for example, a scoring function is +// expensive and you only need to calculate the score of a filtered set of documents. +// +// For more details, see +// https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl-distance-feature-query.html +type DistanceFeatureQuery struct { + field string + pivot string + origin interface{} + boost *float64 + queryName string +} + +// NewDistanceFeatureQuery creates and initializes a new script_score query. +func NewDistanceFeatureQuery(field string, origin interface{}, pivot string) *DistanceFeatureQuery { + return &DistanceFeatureQuery{ + field: field, + origin: origin, + pivot: pivot, + } +} + +// Field to be used in the DistanceFeatureQuery. +func (q *DistanceFeatureQuery) Field(name string) *DistanceFeatureQuery { + q.field = name + return q +} + +// Origin is the date or point of origin used to calculate distances. +// +// If the field is a date or date_nanos field, the origin value must be a +// date. Date math such as "now-1h" is supported. +// +// If the field is a geo_point field, the origin must be a GeoPoint. +func (q *DistanceFeatureQuery) Origin(origin interface{}) *DistanceFeatureQuery { + q.origin = origin + return q +} + +// Pivot is distance from the origin at which relevance scores +// receive half of the boost value. +// +// If field is a date or date_nanos field, the pivot value must be a time +// unit, such as "1h" or "10d". +// +// If field is a geo_point field, the pivot value must be a distance unit, +// such as "1km" or "12m". You can pass a string, or a GeoPoint. +func (q *DistanceFeatureQuery) Pivot(pivot string) *DistanceFeatureQuery { + q.pivot = pivot + return q +} + +// Boost sets the boost for this query. +func (q *DistanceFeatureQuery) Boost(boost float64) *DistanceFeatureQuery { + q.boost = &boost + return q +} + +// QueryName sets the query name for the filter. +func (q *DistanceFeatureQuery) QueryName(queryName string) *DistanceFeatureQuery { + q.queryName = queryName + return q +} + +// Source returns JSON for the function score query. +func (q *DistanceFeatureQuery) Source() (interface{}, error) { + // { + // "distance_feature" : { + // "field" : "production_date", + // "pivot" : "7d", + // "origin" : "now" + // } + // } + // { + // "distance_feature" : { + // "field" : "location", + // "pivot" : "1000m", + // "origin" : [-71.3, 41.15] + // } + // } + + source := make(map[string]interface{}) + query := make(map[string]interface{}) + source["distance_feature"] = query + + query["field"] = q.field + query["pivot"] = q.pivot + switch v := q.origin.(type) { + default: + return nil, fmt.Errorf("DistanceFeatureQuery: unable to serialize Origin from type %T", v) + case string: + query["origin"] = v + case *GeoPoint: + query["origin"] = v.Source() + case GeoPoint: + query["origin"] = v.Source() + } + + if v := q.boost; v != nil { + query["boost"] = *v + } + if q.queryName != "" { + query["_name"] = q.queryName + } + + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_exists.go b/vendor/github.com/olivere/elastic/v7/search_queries_exists.go similarity index 89% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_exists.go rename to vendor/github.com/olivere/elastic/v7/search_queries_exists.go index 1a68393..33f1589 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_exists.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_exists.go @@ -8,13 +8,13 @@ package elastic // has a value in them. // // For more details, see: -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl-exists-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-exists-query.html type ExistsQuery struct { name string queryName string } -// NewExistsQuery creates and initializes a new dis max query. +// NewExistsQuery creates and initializes a new exists query. func NewExistsQuery(name string) *ExistsQuery { return &ExistsQuery{ name: name, diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq.go b/vendor/github.com/olivere/elastic/v7/search_queries_fsq.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq.go rename to vendor/github.com/olivere/elastic/v7/search_queries_fsq.go index 5ad4562..ce00122 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-function-score-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-function-score-query.html type FunctionScoreQuery struct { query Query filter Query @@ -21,7 +21,6 @@ type FunctionScoreQuery struct { filters []Query scoreFuncs []ScoreFunction minScore *float64 - weight *float64 } // NewFunctionScoreQuery creates and initializes a new function score query. diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq_score_funcs.go b/vendor/github.com/olivere/elastic/v7/search_queries_fsq_score_funcs.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq_score_funcs.go rename to vendor/github.com/olivere/elastic/v7/search_queries_fsq_score_funcs.go index 6e86cb4..b14f3b7 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_fsq_score_funcs.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-function-score-query.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_script_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_field_value_factor. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_weight +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/query-dsl-function-score-query.html#_random +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-function-score-query.html#_random // for details. type RandomFunction struct { field string @@ -555,7 +555,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.2/query-dsl-function-score-query.html#_using_function_score +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.v6/search_queries_fuzzy.go b/vendor/github.com/olivere/elastic/v7/search_queries_fuzzy.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_fuzzy.go rename to vendor/github.com/olivere/elastic/v7/search_queries_fuzzy.go index 68b48c1..a81acfc 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_fuzzy.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-fuzzy-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-fuzzy-query.html type FuzzyQuery struct { name string value interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_bounding_box.go b/vendor/github.com/olivere/elastic/v7/search_queries_geo_bounding_box.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_bounding_box.go rename to vendor/github.com/olivere/elastic/v7/search_queries_geo_bounding_box.go index 1cd6bda..6345867 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_bounding_box.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-geo-bounding-box-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-geo-bounding-box-query.html type GeoBoundingBoxQuery struct { name string top *float64 diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_distance.go b/vendor/github.com/olivere/elastic/v7/search_queries_geo_distance.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_distance.go rename to vendor/github.com/olivere/elastic/v7/search_queries_geo_distance.go index 5c5d5fa..4e6878a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_distance.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-geo-distance-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-geo-distance-query.html type GeoDistanceQuery struct { name string distance string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_polygon.go b/vendor/github.com/olivere/elastic/v7/search_queries_geo_polygon.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_polygon.go rename to vendor/github.com/olivere/elastic/v7/search_queries_geo_polygon.go index 9f2ed21..98cd5fe 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_geo_polygon.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-geo-polygon-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-geo-polygon-query.html type GeoPolygonQuery struct { name string points []*GeoPoint diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_has_child.go b/vendor/github.com/olivere/elastic/v7/search_queries_has_child.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_has_child.go rename to vendor/github.com/olivere/elastic/v7/search_queries_has_child.go index b6ae572..d2ce2f9 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_has_child.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-has-child-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-has-child-query.html type HasChildQuery struct { query Query childType string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_has_parent.go b/vendor/github.com/olivere/elastic/v7/search_queries_has_parent.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_has_parent.go rename to vendor/github.com/olivere/elastic/v7/search_queries_has_parent.go index 79afe32..1723f00 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_has_parent.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-has-parent-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-has-parent-query.html type HasParentQuery struct { query Query parentType string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_ids.go b/vendor/github.com/olivere/elastic/v7/search_queries_ids.go similarity index 90% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_ids.go rename to vendor/github.com/olivere/elastic/v7/search_queries_ids.go index bc5d8ae..5192c53 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_ids.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-ids-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.6/query-dsl-ids-query.html type IdsQuery struct { types []string values []string @@ -17,6 +17,9 @@ type IdsQuery struct { } // NewIdsQuery creates and initializes a new ids query. +// +// Notice that types are in the process of being removed. +// You should filter on a field instead. func NewIdsQuery(types ...string) *IdsQuery { return &IdsQuery{ types: types, diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval.go new file mode 100644 index 0000000..d2a9e24 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval.go @@ -0,0 +1,52 @@ +// 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 + +// IntervalQueryRule represents the generic matching interval rule interface. +// Interval Rule is actually just a Query, but may be used only inside +// IntervalQuery. An extra method is added just to shield its +// implementations (*Rule objects) from other query objects. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html +// for details. +type IntervalQueryRule interface { + Query + + // isIntervalQueryRule is never actually called, and is used just for Rule to + // differ from standard Query. + isIntervalQueryRule() bool +} + +// IntervalQuery returns documents based on the order and proximity of matching terms. +// +// For more details, see +// https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html +type IntervalQuery struct { + field string + rule IntervalQueryRule +} + +// NewIntervalQuery creates and initializes a new IntervalQuery. +func NewIntervalQuery(field string, rule IntervalQueryRule) *IntervalQuery { + return &IntervalQuery{field: field, rule: rule} +} + +// Source returns JSON for the function score query. +func (q *IntervalQuery) Source() (interface{}, error) { + // { + // "intervals" : { ... } + // } + source := make(map[string]interface{}) + params := make(map[string]interface{}) + source["intervals"] = params + + src, err := q.rule.Source() + if err != nil { + return nil, err + } + params[q.field] = src + + return source, nil +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_filter.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_filter.go new file mode 100644 index 0000000..d7f0dca --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_filter.go @@ -0,0 +1,175 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryFilter)(nil) +) + +// IntervalQueryFilter specifies filters used in some +// IntervalQueryRule implementations, e.g. IntervalQueryRuleAllOf. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#interval_filter +// for details. +type IntervalQueryFilter struct { + after IntervalQueryRule + before IntervalQueryRule + containedBy IntervalQueryRule + containing IntervalQueryRule + overlapping IntervalQueryRule + notContainedBy IntervalQueryRule + notContaining IntervalQueryRule + notOverlapping IntervalQueryRule + script *Script +} + +// NewIntervalQueryFilter initializes and creates a new +// IntervalQueryFilter. +func NewIntervalQueryFilter() *IntervalQueryFilter { + return &IntervalQueryFilter{} +} + +// After specifies the query to be used to return intervals that follow +// an interval from the filter rule. +func (r *IntervalQueryFilter) After(after IntervalQueryRule) *IntervalQueryFilter { + r.after = after + return r +} + +// Before specifies the query to be used to return intervals that occur +// before an interval from the filter rule. +func (r *IntervalQueryFilter) Before(before IntervalQueryRule) *IntervalQueryFilter { + r.before = before + return r +} + +// ContainedBy specifies the query to be used to return intervals contained +// by an interval from the filter rule. +func (r *IntervalQueryFilter) ContainedBy(containedBy IntervalQueryRule) *IntervalQueryFilter { + r.containedBy = containedBy + return r +} + +// Containing specifies the query to be used to return intervals that contain an +// interval from the filter rule. +func (r *IntervalQueryFilter) Containing(containing IntervalQueryRule) *IntervalQueryFilter { + r.containing = containing + return r +} + +// Overlapping specifies the query to be used to return intervals that overlap +// with an interval from the filter rule. +func (r *IntervalQueryFilter) Overlapping(overlapping IntervalQueryRule) *IntervalQueryFilter { + r.overlapping = overlapping + return r +} + +// NotContainedBy specifies the query to be used to return intervals that are NOT +// contained by an interval from the filter rule. +func (r *IntervalQueryFilter) NotContainedBy(notContainedBy IntervalQueryRule) *IntervalQueryFilter { + r.notContainedBy = notContainedBy + return r +} + +// NotContaining specifies the query to be used to return intervals that do NOT +// contain an interval from the filter rule. +func (r *IntervalQueryFilter) NotContaining(notContaining IntervalQueryRule) *IntervalQueryFilter { + r.notContaining = notContaining + return r +} + +// NotOverlapping specifies the query to be used to return intervals that do NOT +// overlap with an interval from the filter rule. +func (r *IntervalQueryFilter) NotOverlapping(notOverlapping IntervalQueryRule) *IntervalQueryFilter { + r.notOverlapping = notOverlapping + return r +} + +// Script allows a script to be used to return matching documents. The script +// must return a boolean value, true or false. +func (r *IntervalQueryFilter) Script(script *Script) *IntervalQueryFilter { + r.script = script + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryFilter) Source() (interface{}, error) { + source := make(map[string]interface{}) + + if r.before != nil { + src, err := r.before.Source() + if err != nil { + return nil, err + } + source["before"] = src + } + + if r.after != nil { + src, err := r.after.Source() + if err != nil { + return nil, err + } + source["after"] = src + } + + if r.containedBy != nil { + src, err := r.containedBy.Source() + if err != nil { + return nil, err + } + source["contained_by"] = src + } + + if r.containing != nil { + src, err := r.containing.Source() + if err != nil { + return nil, err + } + source["containing"] = src + } + + if r.overlapping != nil { + src, err := r.overlapping.Source() + if err != nil { + return nil, err + } + source["overlapping"] = src + } + + if r.notContainedBy != nil { + src, err := r.notContainedBy.Source() + if err != nil { + return nil, err + } + source["not_contained_by"] = src + } + + if r.notContaining != nil { + src, err := r.notContaining.Source() + if err != nil { + return nil, err + } + source["not_containing"] = src + } + + if r.notOverlapping != nil { + src, err := r.notOverlapping.Source() + if err != nil { + return nil, err + } + source["not_overlapping"] = src + } + + if r.script != nil { + src, err := r.script.Source() + if err != nil { + return nil, err + } + source["script"] = src + } + + return source, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryFilter) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_all_of.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_all_of.go new file mode 100644 index 0000000..99314bb --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_all_of.go @@ -0,0 +1,82 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryRuleAllOf)(nil) +) + +// IntervalQueryRuleAllOf is an implementation of IntervalQueryRule. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#intervals-all_of +// for details. +type IntervalQueryRuleAllOf struct { + intervals []IntervalQueryRule + maxGaps *int + ordered *bool + filter *IntervalQueryFilter +} + +// NewIntervalQueryRuleAllOf initializes and returns a new instance +// of IntervalQueryRuleAllOf. +func NewIntervalQueryRuleAllOf(intervals ...IntervalQueryRule) *IntervalQueryRuleAllOf { + return &IntervalQueryRuleAllOf{intervals: intervals} +} + +// MaxGaps specifies the maximum number of positions between the matching +// terms. Terms further apart than this are considered matches. Defaults to -1. +func (r *IntervalQueryRuleAllOf) MaxGaps(maxGaps int) *IntervalQueryRuleAllOf { + r.maxGaps = &maxGaps + return r +} + +// Ordered, if true, indicates that matching terms must appear in their specified +// order. Defaults to false. +func (r *IntervalQueryRuleAllOf) Ordered(ordered bool) *IntervalQueryRuleAllOf { + r.ordered = &ordered + return r +} + +// Filter adds an additional interval filter. +func (r *IntervalQueryRuleAllOf) Filter(filter *IntervalQueryFilter) *IntervalQueryRuleAllOf { + r.filter = filter + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryRuleAllOf) Source() (interface{}, error) { + source := make(map[string]interface{}) + + intervalSources := make([]interface{}, 0) + for _, interval := range r.intervals { + src, err := interval.Source() + if err != nil { + return nil, err + } + + intervalSources = append(intervalSources, src) + } + source["intervals"] = intervalSources + + if r.ordered != nil { + source["ordered"] = *r.ordered + } + if r.maxGaps != nil { + source["max_gaps"] = *r.maxGaps + } + if r.filter != nil { + src, err := r.filter.Source() + if err != nil { + return nil, err + } + + source["filter"] = src + } + + return map[string]interface{}{ + "all_of": source, + }, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryRuleAllOf) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_any_of.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_any_of.go new file mode 100644 index 0000000..1009247 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_any_of.go @@ -0,0 +1,60 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryRuleAnyOf)(nil) +) + +// IntervalQueryRuleAnyOf is an implementation of IntervalQueryRule. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#intervals-any_of +// for details. +type IntervalQueryRuleAnyOf struct { + intervals []IntervalQueryRule + filter *IntervalQueryFilter +} + +// NewIntervalQueryRuleAnyOf initializes and returns a new instance +// of IntervalQueryRuleAnyOf. +func NewIntervalQueryRuleAnyOf(intervals ...IntervalQueryRule) *IntervalQueryRuleAnyOf { + return &IntervalQueryRuleAnyOf{intervals: intervals} +} + +// Filter adds an additional interval filter. +func (r *IntervalQueryRuleAnyOf) Filter(filter *IntervalQueryFilter) *IntervalQueryRuleAnyOf { + r.filter = filter + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryRuleAnyOf) Source() (interface{}, error) { + source := make(map[string]interface{}) + + var intervalSources []interface{} + for _, interval := range r.intervals { + src, err := interval.Source() + if err != nil { + return nil, err + } + + intervalSources = append(intervalSources, src) + } + source["intervals"] = intervalSources + + if r.filter != nil { + src, err := r.filter.Source() + if err != nil { + return nil, err + } + + source["filter"] = src + } + + return map[string]interface{}{ + "any_of": source, + }, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryRuleAnyOf) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_match.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_match.go new file mode 100644 index 0000000..be07ca2 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_match.go @@ -0,0 +1,94 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryRuleMatch)(nil) +) + +// IntervalQueryRuleMatch is an implementation of IntervalQueryRule. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#intervals-match +// for details. +type IntervalQueryRuleMatch struct { + query string + maxGaps *int + ordered *bool + analyzer string + useField string + filter *IntervalQueryFilter +} + +// NewIntervalQueryRuleMatch initializes and returns a new instance +// of IntervalQueryRuleMatch. +func NewIntervalQueryRuleMatch(query string) *IntervalQueryRuleMatch { + return &IntervalQueryRuleMatch{query: query} +} + +// MaxGaps specifies the maximum number of positions between the matching +// terms. Terms further apart than this are considered matches. Defaults to -1. +func (r *IntervalQueryRuleMatch) MaxGaps(maxGaps int) *IntervalQueryRuleMatch { + r.maxGaps = &maxGaps + return r +} + +// Ordered, if true, indicates that matching terms must appear in their specified +// order. Defaults to false. +func (r *IntervalQueryRuleMatch) Ordered(ordered bool) *IntervalQueryRuleMatch { + r.ordered = &ordered + return r +} + +// Analyzer specifies the analyzer used to analyze terms in the query. +func (r *IntervalQueryRuleMatch) Analyzer(analyzer string) *IntervalQueryRuleMatch { + r.analyzer = analyzer + return r +} + +// UseField, if specified, matches the intervals from this field rather than +// the top-level field. +func (r *IntervalQueryRuleMatch) UseField(useField string) *IntervalQueryRuleMatch { + r.useField = useField + return r +} + +// Filter adds an additional interval filter. +func (r *IntervalQueryRuleMatch) Filter(filter *IntervalQueryFilter) *IntervalQueryRuleMatch { + r.filter = filter + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryRuleMatch) Source() (interface{}, error) { + source := make(map[string]interface{}) + + source["query"] = r.query + + if r.ordered != nil { + source["ordered"] = *r.ordered + } + if r.maxGaps != nil { + source["max_gaps"] = *r.maxGaps + } + if r.analyzer != "" { + source["analyzer"] = r.analyzer + } + if r.useField != "" { + source["use_field"] = r.useField + } + if r.filter != nil { + filterRuleSource, err := r.filter.Source() + if err != nil { + return nil, err + } + + source["filter"] = filterRuleSource + } + + return map[string]interface{}{ + "match": source, + }, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryRuleMatch) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_prefix.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_prefix.go new file mode 100644 index 0000000..7eea791 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_prefix.go @@ -0,0 +1,57 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryRulePrefix)(nil) +) + +// IntervalQueryRulePrefix is an implementation of IntervalQueryRule. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#intervals-prefix +// for details. +type IntervalQueryRulePrefix struct { + prefix string + analyzer string + useField string +} + +// NewIntervalQueryRulePrefix initializes and returns a new instance +// of IntervalQueryRulePrefix. +func NewIntervalQueryRulePrefix(prefix string) *IntervalQueryRulePrefix { + return &IntervalQueryRulePrefix{prefix: prefix} +} + +// Analyzer specifies the analyzer used to analyze terms in the query. +func (r *IntervalQueryRulePrefix) Analyzer(analyzer string) *IntervalQueryRulePrefix { + r.analyzer = analyzer + return r +} + +// UseField, if specified, matches the intervals from this field rather than +// the top-level field. +func (r *IntervalQueryRulePrefix) UseField(useField string) *IntervalQueryRulePrefix { + r.useField = useField + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryRulePrefix) Source() (interface{}, error) { + source := make(map[string]interface{}) + + source["query"] = r.prefix + + if r.analyzer != "" { + source["analyzer"] = r.analyzer + } + if r.useField != "" { + source["use_field"] = r.useField + } + + return map[string]interface{}{ + "prefix": source, + }, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryRulePrefix) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_wildcard.go b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_wildcard.go new file mode 100644 index 0000000..8978852 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_wildcard.go @@ -0,0 +1,57 @@ +package elastic + +var ( + _ IntervalQueryRule = (*IntervalQueryRuleWildcard)(nil) +) + +// IntervalQueryRuleWildcard is an implementation of IntervalQueryRule. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/query-dsl-intervals-query.html#intervals-wildcard +// for details. +type IntervalQueryRuleWildcard struct { + pattern string + analyzer string + useField string +} + +// NewIntervalQueryRuleWildcard initializes and returns a new instance +// of IntervalQueryRuleWildcard. +func NewIntervalQueryRuleWildcard(pattern string) *IntervalQueryRuleWildcard { + return &IntervalQueryRuleWildcard{pattern: pattern} +} + +// Analyzer specifies the analyzer used to analyze terms in the query. +func (r *IntervalQueryRuleWildcard) Analyzer(analyzer string) *IntervalQueryRuleWildcard { + r.analyzer = analyzer + return r +} + +// UseField, if specified, matches the intervals from this field rather than +// the top-level field. +func (r *IntervalQueryRuleWildcard) UseField(useField string) *IntervalQueryRuleWildcard { + r.useField = useField + return r +} + +// Source returns JSON for the function score query. +func (r *IntervalQueryRuleWildcard) Source() (interface{}, error) { + source := make(map[string]interface{}) + + source["pattern"] = r.pattern + + if r.analyzer != "" { + source["analyzer"] = r.analyzer + } + if r.useField != "" { + source["use_field"] = r.useField + } + + return map[string]interface{}{ + "wildcard": source, + }, nil +} + +// isIntervalQueryRule implements the marker interface. +func (r *IntervalQueryRuleWildcard) isIntervalQueryRule() bool { + return true +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match.go b/vendor/github.com/olivere/elastic/v7/search_queries_match.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_match.go rename to vendor/github.com/olivere/elastic/v7/search_queries_match.go index 875e259..fce1078 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-match-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-match-query.html type MatchQuery struct { name string text interface{} @@ -176,7 +176,7 @@ func (q *MatchQuery) Source() (interface{}, error) { query["zero_terms_query"] = q.zeroTermsQuery } if q.cutoffFrequency != nil { - query["cutoff_frequency"] = q.cutoffFrequency + query["cutoff_frequency"] = *q.cutoffFrequency } if q.boost != nil { query["boost"] = *q.boost diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_all.go b/vendor/github.com/olivere/elastic/v7/search_queries_match_all.go similarity index 95% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_match_all.go rename to vendor/github.com/olivere/elastic/v7/search_queries_match_all.go index d43e857..921ead5 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_all.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-match-all-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-match-all-query.html type MatchAllQuery struct { boost *float64 queryName string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_none.go b/vendor/github.com/olivere/elastic/v7/search_queries_match_none.go similarity index 93% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_match_none.go rename to vendor/github.com/olivere/elastic/v7/search_queries_match_none.go index 6d675c1..a1d1f87 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_none.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-match-all-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-match-all-query.html type MatchNoneQuery struct { queryName string } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase.go b/vendor/github.com/olivere/elastic/v7/search_queries_match_phrase.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase.go rename to vendor/github.com/olivere/elastic/v7/search_queries_match_phrase.go index 58c3c07..974a49a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-match-query-phrase.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-match-query-phrase.html type MatchPhraseQuery struct { name string value interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase_prefix.go b/vendor/github.com/olivere/elastic/v7/search_queries_match_phrase_prefix.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase_prefix.go rename to vendor/github.com/olivere/elastic/v7/search_queries_match_phrase_prefix.go index 93a28cc..fb366d3 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_match_phrase_prefix.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-match-query-phrase-prefix.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-match-query-phrase-prefix.html type MatchPhrasePrefixQuery struct { name string value interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_more_like_this.go b/vendor/github.com/olivere/elastic/v7/search_queries_more_like_this.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_more_like_this.go rename to vendor/github.com/olivere/elastic/v7/search_queries_more_like_this.go index 1a904ee..0ee389b 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_more_like_this.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-mlt-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-mlt-query.html type MoreLikeThisQuery struct { fields []string docs []*MoreLikeThisQueryItem @@ -320,6 +320,8 @@ func (item *MoreLikeThisQueryItem) Index(index string) *MoreLikeThisQueryItem { } // Type represents the document type of the item. +// +// Deprecated: Types are in the process of being removed. func (item *MoreLikeThisQueryItem) Type(typ string) *MoreLikeThisQueryItem { item.typ = typ return item @@ -392,7 +394,7 @@ func (item *MoreLikeThisQueryItem) Source() (interface{}, error) { source["fields"] = item.fields } if item.routing != "" { - source["_routing"] = item.routing + source["routing"] = item.routing } if item.fsc != nil { src, err := item.fsc.Source() diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_multi_match.go b/vendor/github.com/olivere/elastic/v7/search_queries_multi_match.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_multi_match.go rename to vendor/github.com/olivere/elastic/v7/search_queries_multi_match.go index 1a8df17..48c5f28 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_multi_match.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-multi-match-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-multi-match-query.html type MultiMatchQuery struct { text interface{} fields []string @@ -60,7 +60,7 @@ func (q *MultiMatchQuery) FieldWithBoost(field string, boost float64) *MultiMatc } // Type can be "best_fields", "boolean", "most_fields", "cross_fields", -// "phrase", or "phrase_prefix". +// "phrase", "phrase_prefix" or "bool_prefix" func (q *MultiMatchQuery) Type(typ string) *MultiMatchQuery { var zero = float64(0.0) var one = float64(1.0) @@ -81,6 +81,9 @@ func (q *MultiMatchQuery) Type(typ string) *MultiMatchQuery { case "phrase_prefix": q.typ = "phrase_prefix" q.tieBreaker = &zero + case "bool_prefix": + q.typ = "bool_prefix" + q.tieBreaker = &zero } return q } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_nested.go b/vendor/github.com/olivere/elastic/v7/search_queries_nested.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_nested.go rename to vendor/github.com/olivere/elastic/v7/search_queries_nested.go index cdd3f8b..211649d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_nested.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-nested-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-nested-query.html type NestedQuery struct { query Query path string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_parent_id.go b/vendor/github.com/olivere/elastic/v7/search_queries_parent_id.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_parent_id.go rename to vendor/github.com/olivere/elastic/v7/search_queries_parent_id.go index b015d36..46a4999 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_parent_id.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-parent-id-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-parent-id-query.html type ParentIdQuery struct { typ string id string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_percolator.go b/vendor/github.com/olivere/elastic/v7/search_queries_percolator.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_percolator.go rename to vendor/github.com/olivere/elastic/v7/search_queries_percolator.go index a6c53f4..5a459d0 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_percolator.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_percolator.go @@ -9,11 +9,12 @@ 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.2/query-dsl-percolate-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-percolate-query.html type PercolatorQuery struct { field string + name string documentType string // deprecated - document interface{} + documents []interface{} indexedDocumentIndex string indexedDocumentType string indexedDocumentId string @@ -32,14 +33,21 @@ func (q *PercolatorQuery) Field(field string) *PercolatorQuery { return q } +// Name used for identification purposes in "_percolator_document_slot" response +// field when multiple percolate queries have been specified in the main query. +func (q *PercolatorQuery) Name(name string) *PercolatorQuery { + q.name = name + return q +} + // Deprecated: DocumentType is deprecated as of 6.0. func (q *PercolatorQuery) DocumentType(typ string) *PercolatorQuery { q.documentType = typ return q } -func (q *PercolatorQuery) Document(doc interface{}) *PercolatorQuery { - q.document = doc +func (q *PercolatorQuery) Document(docs ...interface{}) *PercolatorQuery { + q.documents = append(q.documents, docs...) return q } @@ -78,9 +86,6 @@ func (q *PercolatorQuery) Source() (interface{}, error) { if len(q.field) == 0 { return nil, errors.New("elastic: Field is required in PercolatorQuery") } - if q.document == nil { - return nil, errors.New("elastic: Document is required in PercolatorQuery") - } // { // "percolate" : { ... } @@ -92,24 +97,35 @@ func (q *PercolatorQuery) Source() (interface{}, error) { if q.documentType != "" { params["document_type"] = q.documentType } - params["document"] = q.document - if len(q.indexedDocumentIndex) > 0 { - params["index"] = q.indexedDocumentIndex + if q.name != "" { + params["name"] = q.name + } + + switch len(q.documents) { + case 0: + case 1: + params["document"] = q.documents[0] + default: + params["documents"] = q.documents + } + + if s := q.indexedDocumentIndex; s != "" { + params["index"] = s } - if len(q.indexedDocumentType) > 0 { - params["type"] = q.indexedDocumentType + if s := q.indexedDocumentType; s != "" { + params["type"] = s } - if len(q.indexedDocumentId) > 0 { - params["id"] = q.indexedDocumentId + if s := q.indexedDocumentId; s != "" { + params["id"] = s } - if len(q.indexedDocumentRouting) > 0 { - params["routing"] = q.indexedDocumentRouting + if s := q.indexedDocumentRouting; s != "" { + params["routing"] = s } - if len(q.indexedDocumentPreference) > 0 { - params["preference"] = q.indexedDocumentPreference + if s := q.indexedDocumentPreference; s != "" { + params["preference"] = s } - if q.indexedDocumentVersion != nil { - params["version"] = *q.indexedDocumentVersion + if v := q.indexedDocumentVersion; v != nil { + params["version"] = *v } return source, nil } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_prefix.go b/vendor/github.com/olivere/elastic/v7/search_queries_prefix.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_prefix.go rename to vendor/github.com/olivere/elastic/v7/search_queries_prefix.go index 713bcec..8178aac 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_prefix.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-prefix-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-prefix-query.html type PrefixQuery struct { name string prefix string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_query_string.go b/vendor/github.com/olivere/elastic/v7/search_queries_query_string.go similarity index 99% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_query_string.go rename to vendor/github.com/olivere/elastic/v7/search_queries_query_string.go index 485930d..f9baa21 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_query_string.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_query_string.go @@ -11,7 +11,7 @@ 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.2/query-dsl-query-string-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-query-string-query.html type QueryStringQuery struct { queryString string defaultField string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_range.go b/vendor/github.com/olivere/elastic/v7/search_queries_range.go similarity index 98% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_range.go rename to vendor/github.com/olivere/elastic/v7/search_queries_range.go index 5ab4636..e3c0730 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_range.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-range-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-range-query.html type RangeQuery struct { name string from interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_raw_string.go b/vendor/github.com/olivere/elastic/v7/search_queries_raw_string.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_raw_string.go rename to vendor/github.com/olivere/elastic/v7/search_queries_raw_string.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_regexp.go b/vendor/github.com/olivere/elastic/v7/search_queries_regexp.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_regexp.go rename to vendor/github.com/olivere/elastic/v7/search_queries_regexp.go index f9234de..25a0c3d 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_regexp.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-regexp-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-regexp-query.html type RegexpQuery struct { name string regexp string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_script.go b/vendor/github.com/olivere/elastic/v7/search_queries_script.go similarity index 95% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_script.go rename to vendor/github.com/olivere/elastic/v7/search_queries_script.go index b75e318..d99b0c0 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_script.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-script-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-script-query.html type ScriptQuery struct { script *Script queryName string diff --git a/vendor/github.com/olivere/elastic/v7/search_queries_script_score.go b/vendor/github.com/olivere/elastic/v7/search_queries_script_score.go new file mode 100644 index 0000000..7f00e0f --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_queries_script_score.go @@ -0,0 +1,110 @@ +// 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 "errors" + +// ScriptScoreQuery uses a script to provide a custom score for returned documents. +// +// A ScriptScoreQuery query is useful if, for example, a scoring function is +// expensive and you only need to calculate the score of a filtered set of documents. +// +// For more details, see +// https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl-script-score-query.html +type ScriptScoreQuery struct { + query Query + script *Script + minScore *float64 + boost *float64 + queryName string +} + +// NewScriptScoreQuery creates and initializes a new script_score query. +func NewScriptScoreQuery(query Query, script *Script) *ScriptScoreQuery { + return &ScriptScoreQuery{ + query: query, + script: script, + } +} + +// Query to be used in the ScriptScoreQuery. +func (q *ScriptScoreQuery) Query(query Query) *ScriptScoreQuery { + q.query = query + return q +} + +// Script to calculate the score. +func (q *ScriptScoreQuery) Script(script *Script) *ScriptScoreQuery { + q.script = script + return q +} + +// MinScore sets the minimum score. +func (q *ScriptScoreQuery) MinScore(minScore float64) *ScriptScoreQuery { + q.minScore = &minScore + return q +} + +// Boost sets the boost for this query. +func (q *ScriptScoreQuery) Boost(boost float64) *ScriptScoreQuery { + q.boost = &boost + return q +} + +// QueryName sets the query name for the filter. +func (q *ScriptScoreQuery) QueryName(queryName string) *ScriptScoreQuery { + q.queryName = queryName + return q +} + +// Source returns JSON for the function score query. +func (q *ScriptScoreQuery) Source() (interface{}, error) { + // { + // "script_score" : { + // "query" : { + // "match" : { "message": "elasticsearch" } + // }, + // "script" : { + // "source" : "doc['likes'].value / 10" + // } + // } + // } + + source := make(map[string]interface{}) + query := make(map[string]interface{}) + source["script_score"] = query + + if q.query == nil { + return nil, errors.New("ScriptScoreQuery: Query is missing") + } + if q.script == nil { + return nil, errors.New("ScriptScoreQuery: Script is missing") + } + + if src, err := q.query.Source(); err != nil { + return nil, err + } else { + query["query"] = src + } + + if src, err := q.script.Source(); err != nil { + return nil, err + } else { + query["script"] = src + } + + if v := q.minScore; v != nil { + query["min_score"] = *v + } + + if v := q.boost; v != nil { + query["boost"] = *v + } + if q.queryName != "" { + query["_name"] = q.queryName + } + + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_simple_query_string.go b/vendor/github.com/olivere/elastic/v7/search_queries_simple_query_string.go similarity index 99% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_simple_query_string.go rename to vendor/github.com/olivere/elastic/v7/search_queries_simple_query_string.go index 0ec8c4a..230e041 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_simple_query_string.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-simple-query-string-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-simple-query-string-query.html type SimpleQueryStringQuery struct { queryText string analyzer string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_slice.go b/vendor/github.com/olivere/elastic/v7/search_queries_slice.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_slice.go rename to vendor/github.com/olivere/elastic/v7/search_queries_slice.go index 0f58fb5..0eac784 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_slice.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-request-scroll.html#sliced-scroll +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-scroll.html#sliced-scroll // for details. type SliceQuery struct { field string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_term.go b/vendor/github.com/olivere/elastic/v7/search_queries_term.go similarity index 95% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_term.go rename to vendor/github.com/olivere/elastic/v7/search_queries_term.go index d495fda..832e67e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_term.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-term-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-term-query.html type TermQuery struct { name string value interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_terms.go b/vendor/github.com/olivere/elastic/v7/search_queries_terms.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_terms.go rename to vendor/github.com/olivere/elastic/v7/search_queries_terms.go index aaa47e8..b8171cd 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_terms.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-terms-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-terms-query.html type TermsQuery struct { name string values []interface{} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_terms_set.go b/vendor/github.com/olivere/elastic/v7/search_queries_terms_set.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_terms_set.go rename to vendor/github.com/olivere/elastic/v7/search_queries_terms_set.go index 22afcb8..6a33a2a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_terms_set.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_terms_set.go @@ -12,7 +12,7 @@ package elastic // minimum should match script. // // For more details, see -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl-terms-set-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-terms-set-query.html type TermsSetQuery struct { name string values []interface{} @@ -25,7 +25,8 @@ type TermsSetQuery struct { // NewTermsSetQuery creates and initializes a new TermsSetQuery. func NewTermsSetQuery(name string, values ...interface{}) *TermsSetQuery { q := &TermsSetQuery{ - name: name, + name: name, + values: make([]interface{}, 0), } if len(values) > 0 { q.values = append(q.values, values...) diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_type.go b/vendor/github.com/olivere/elastic/v7/search_queries_type.go similarity index 91% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_type.go rename to vendor/github.com/olivere/elastic/v7/search_queries_type.go index 3ca8d50..61867c1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_type.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-type-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-type-query.html type TypeQuery struct { typ string } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_wildcard.go b/vendor/github.com/olivere/elastic/v7/search_queries_wildcard.go similarity index 96% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_wildcard.go rename to vendor/github.com/olivere/elastic/v7/search_queries_wildcard.go index de7da66..33e4ea2 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_wildcard.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-wildcard-query.html +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-wildcard-query.html type WildcardQuery struct { name string wildcard string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_queries_wrapper.go b/vendor/github.com/olivere/elastic/v7/search_queries_wrapper.go similarity index 92% rename from vendor/gopkg.in/olivere/elastic.v6/search_queries_wrapper.go rename to vendor/github.com/olivere/elastic/v7/search_queries_wrapper.go index b45c677..2a32d1e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_queries_wrapper.go +++ b/vendor/github.com/olivere/elastic/v7/search_queries_wrapper.go @@ -7,7 +7,7 @@ package elastic // WrapperQuery accepts any other query as base64 encoded string. // // For details, see -// https://www.elastic.co/guide/en/elasticsearch/reference/6.3/query-dsl-wrapper-query.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-wrapper-query.html. type WrapperQuery struct { source string } diff --git a/vendor/github.com/olivere/elastic/v7/search_request.go b/vendor/github.com/olivere/elastic/v7/search_request.go new file mode 100644 index 0000000..3a444b8 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/search_request.go @@ -0,0 +1,586 @@ +// 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" + "strings" +) + +// SearchRequest combines a search request and its +// query details (see SearchSource). +// It is used in combination with MultiSearch. +type SearchRequest struct { + searchType string + indices []string + types []string + routing *string + preference *string + requestCache *bool + allowPartialSearchResults *bool + ignoreUnavailable *bool + allowNoIndices *bool + expandWildcards string + scroll string + source interface{} + searchSource *SearchSource + batchedReduceSize *int + maxConcurrentShardRequests *int + preFilterShardSize *int +} + +// NewSearchRequest creates a new search request. +func NewSearchRequest() *SearchRequest { + return &SearchRequest{ + searchSource: NewSearchSource(), + } +} + +// SearchType must be one of "dfs_query_then_fetch", "dfs_query_and_fetch", +// "query_then_fetch", or "query_and_fetch". +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") +} + +// SearchTypeQueryThenFetch sets search type to "query_then_fetch". +func (r *SearchRequest) SearchTypeQueryThenFetch() *SearchRequest { + return r.SearchType("query_then_fetch") +} + +// Index specifies the indices to use in the request. +func (r *SearchRequest) Index(indices ...string) *SearchRequest { + r.indices = append(r.indices, indices...) + return r +} + +// HasIndices returns true if there are indices used, false otherwise. +func (r *SearchRequest) HasIndices() bool { + return len(r.indices) > 0 +} + +// Type specifies one or more types to be used. +// +// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to +// filter on a field on the document. +func (r *SearchRequest) Type(types ...string) *SearchRequest { + r.types = append(r.types, types...) + return r +} + +// Routing specifies the routing parameter. It is a comma-separated list. +func (r *SearchRequest) Routing(routing string) *SearchRequest { + r.routing = &routing + return r +} + +// Routings to be used in the request. +func (r *SearchRequest) Routings(routings ...string) *SearchRequest { + if routings != nil { + routings := strings.Join(routings, ",") + r.routing = &routings + } else { + r.routing = nil + } + return r +} + +// Preference to execute the search. Defaults to randomize across shards. +// Can be set to "_local" to prefer local shards, "_primary" to execute +// only on primary shards, or a custom value, which guarantees that the +// same order will be used across different requests. +func (r *SearchRequest) Preference(preference string) *SearchRequest { + r.preference = &preference + return r +} + +// RequestCache specifies if this request should use the request cache +// or not, assuming that it can. By default, will default to the index +// level setting if request cache is enabled or not. +func (r *SearchRequest) RequestCache(requestCache bool) *SearchRequest { + r.requestCache = &requestCache + return r +} + +// IgnoreUnavailable indicates whether specified concrete indices should be +// ignored when unavailable (missing or closed). +func (s *SearchRequest) IgnoreUnavailable(ignoreUnavailable bool) *SearchRequest { + 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 *SearchRequest) AllowNoIndices(allowNoIndices bool) *SearchRequest { + s.allowNoIndices = &allowNoIndices + return s +} + +// ExpandWildcards indicates whether to expand wildcard expression to +// concrete indices that are open, closed or both. +func (s *SearchRequest) ExpandWildcards(expandWildcards string) *SearchRequest { + s.expandWildcards = expandWildcards + return s +} + +// Scroll, if set, will enable scrolling of the search request. +// Pass a timeout value, e.g. "2m" or "30s" as a value. +func (r *SearchRequest) Scroll(scroll string) *SearchRequest { + r.scroll = scroll + return r +} + +// SearchSource allows passing your own SearchSource, overriding +// all values set on the request (except Source). +func (r *SearchRequest) SearchSource(searchSource *SearchSource) *SearchRequest { + if searchSource == nil { + r.searchSource = NewSearchSource() + return r + } + r.searchSource = searchSource + return r +} + +// Source allows passing your own request body. It will have preference over +// all other properties set on the request. +func (r *SearchRequest) Source(source interface{}) *SearchRequest { + r.source = source + return r +} + +// Timeout value for the request, e.g. "30s" or "2m". +func (r *SearchRequest) Timeout(timeout string) *SearchRequest { + r.searchSource = r.searchSource.Timeout(timeout) + return r +} + +// TerminateAfter, when set, specifies an optional document count, +// upon collecting which the search query will terminate early. +func (r *SearchRequest) TerminateAfter(docs int) *SearchRequest { + r.searchSource = r.searchSource.TerminateAfter(docs) + return r +} + +// Query for the search. +func (r *SearchRequest) Query(query Query) *SearchRequest { + r.searchSource = r.searchSource.Query(query) + return r +} + +// PostFilter is a filter that will be executed after the query +// has been executed and only has affect on the search hits +// (not aggregations). This filter is always executed as last +// filtering mechanism. +func (r *SearchRequest) PostFilter(filter Query) *SearchRequest { + r.searchSource = r.searchSource.PostFilter(filter) + return r +} + +// MinScore below which documents are filtered out. +func (r *SearchRequest) MinScore(minScore float64) *SearchRequest { + r.searchSource = r.searchSource.MinScore(minScore) + return r +} + +// From index to start search from (default is 0). +func (r *SearchRequest) From(from int) *SearchRequest { + r.searchSource = r.searchSource.From(from) + return r +} + +// Size is the number of search hits to return (default is 10). +func (r *SearchRequest) Size(size int) *SearchRequest { + r.searchSource = r.searchSource.Size(size) + return r +} + +// Explain indicates whether to return an explanation for each hit. +func (r *SearchRequest) Explain(explain bool) *SearchRequest { + r.searchSource = r.searchSource.Explain(explain) + return r +} + +// Version indicates whether each hit should be returned with +// its version. +func (r *SearchRequest) Version(version bool) *SearchRequest { + r.searchSource = r.searchSource.Version(version) + return r +} + +// IndexBoost sets a boost a specific index will receive when +// the query is executed against it. +func (r *SearchRequest) IndexBoost(index string, boost float64) *SearchRequest { + r.searchSource = r.searchSource.IndexBoost(index, boost) + return r +} + +// Stats groups that this request will be aggregated under. +func (r *SearchRequest) Stats(statsGroup ...string) *SearchRequest { + r.searchSource = r.searchSource.Stats(statsGroup...) + return r +} + +// FetchSource indicates whether the response should contain the stored +// _source for every hit. +func (r *SearchRequest) FetchSource(fetchSource bool) *SearchRequest { + r.searchSource = r.searchSource.FetchSource(fetchSource) + return r +} + +// FetchSourceIncludeExclude specifies that _source should be returned +// with each hit, where "include" and "exclude" serve as a simple wildcard +// matcher that gets applied to its fields +// (e.g. include := []string{"obj1.*","obj2.*"}, exclude := []string{"description.*"}). +func (r *SearchRequest) FetchSourceIncludeExclude(include, exclude []string) *SearchRequest { + r.searchSource = r.searchSource.FetchSourceIncludeExclude(include, exclude) + return r +} + +// FetchSourceContext indicates how the _source should be fetched. +func (r *SearchRequest) FetchSourceContext(fsc *FetchSourceContext) *SearchRequest { + r.searchSource = r.searchSource.FetchSourceContext(fsc) + return r +} + +// DocValueField adds a docvalue based field to load and return. +// The field does not have to be stored, but it's recommended to use +// non analyzed or numeric fields. +func (r *SearchRequest) DocValueField(field string) *SearchRequest { + r.searchSource = r.searchSource.DocvalueField(field) + return r +} + +// DocValueFieldWithFormat adds a docvalue based field to load and return. +// The field does not have to be stored, but it's recommended to use +// non analyzed or numeric fields. +func (r *SearchRequest) DocValueFieldWithFormat(field DocvalueField) *SearchRequest { + r.searchSource = r.searchSource.DocvalueFieldWithFormat(field) + return r +} + +// DocValueFields adds one or more docvalue based field to load and return. +// The fields do not have to be stored, but it's recommended to use +// non analyzed or numeric fields. +func (r *SearchRequest) DocValueFields(fields ...string) *SearchRequest { + r.searchSource = r.searchSource.DocvalueFields(fields...) + return r +} + +// DocValueFieldsWithFormat adds one or more docvalue based field to load and return. +// The fields do not have to be stored, but it's recommended to use +// non analyzed or numeric fields. +func (r *SearchRequest) DocValueFieldsWithFormat(fields ...DocvalueField) *SearchRequest { + r.searchSource = r.searchSource.DocvalueFieldsWithFormat(fields...) + return r +} + +// StoredField adds a stored field to load and return +// (note, it must be stored) as part of the search request. +func (r *SearchRequest) StoredField(field string) *SearchRequest { + r.searchSource = r.searchSource.StoredField(field) + return r +} + +// NoStoredFields indicates that no fields should be loaded, +// resulting in only id and type to be returned per field. +func (r *SearchRequest) NoStoredFields() *SearchRequest { + r.searchSource = r.searchSource.NoStoredFields() + return r +} + +// StoredFields adds one or more stored field to load and return +// (note, they must be stored) as part of the search request. +func (r *SearchRequest) StoredFields(fields ...string) *SearchRequest { + r.searchSource = r.searchSource.StoredFields(fields...) + return r +} + +// ScriptField adds a script based field to load and return. +// The field does not have to be stored, but it's recommended +// to use non analyzed or numeric fields. +func (r *SearchRequest) ScriptField(field *ScriptField) *SearchRequest { + r.searchSource = r.searchSource.ScriptField(field) + return r +} + +// ScriptFields adds one or more script based field to load and return. +// The fields do not have to be stored, but it's recommended +// to use non analyzed or numeric fields. +func (r *SearchRequest) ScriptFields(fields ...*ScriptField) *SearchRequest { + r.searchSource = r.searchSource.ScriptFields(fields...) + return r +} + +// Sort adds a sort order. +func (r *SearchRequest) Sort(field string, ascending bool) *SearchRequest { + r.searchSource = r.searchSource.Sort(field, ascending) + return r +} + +// SortWithInfo adds a sort order. +func (r *SearchRequest) SortWithInfo(info SortInfo) *SearchRequest { + r.searchSource = r.searchSource.SortWithInfo(info) + return r +} + +// SortBy adds a sort order. +func (r *SearchRequest) SortBy(sorter ...Sorter) *SearchRequest { + r.searchSource = r.searchSource.SortBy(sorter...) + return r +} + +// SearchAfter sets the sort values that indicates which docs this +// request should "search after". +func (r *SearchRequest) SearchAfter(sortValues ...interface{}) *SearchRequest { + r.searchSource = r.searchSource.SearchAfter(sortValues...) + return r +} + +// 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/7.0/search-request-scroll.html#sliced-scroll +// for details. +func (r *SearchRequest) Slice(sliceQuery Query) *SearchRequest { + r.searchSource = r.searchSource.Slice(sliceQuery) + return r +} + +// TrackScores is applied when sorting and controls if scores will be +// tracked as well. Defaults to false. +func (r *SearchRequest) TrackScores(trackScores bool) *SearchRequest { + r.searchSource = r.searchSource.TrackScores(trackScores) + return r +} + +// TrackTotalHits indicates if the total hit count for the query should be tracked. +// Defaults to true. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-track-total-hits.html +// for details. +func (r *SearchRequest) TrackTotalHits(trackTotalHits interface{}) *SearchRequest { + r.searchSource = r.searchSource.TrackTotalHits(trackTotalHits) + return r +} + +// Aggregation adds an aggreation to perform as part of the search. +func (r *SearchRequest) Aggregation(name string, aggregation Aggregation) *SearchRequest { + r.searchSource = r.searchSource.Aggregation(name, aggregation) + return r +} + +// Highlight adds highlighting to the search. +func (r *SearchRequest) Highlight(highlight *Highlight) *SearchRequest { + r.searchSource = r.searchSource.Highlight(highlight) + return r +} + +// Suggester adds a suggester to the search. +func (r *SearchRequest) Suggester(suggester Suggester) *SearchRequest { + r.searchSource = r.searchSource.Suggester(suggester) + return r +} + +// Rescorer adds a rescorer to the search. +func (r *SearchRequest) Rescorer(rescore *Rescore) *SearchRequest { + r.searchSource = r.searchSource.Rescorer(rescore) + return r +} + +// ClearRescorers removes all rescorers from the search. +func (r *SearchRequest) ClearRescorers() *SearchRequest { + r.searchSource = r.searchSource.ClearRescorers() + return r +} + +// Profile specifies that this search source should activate the +// Profile API for queries made on it. +func (r *SearchRequest) Profile(profile bool) *SearchRequest { + r.searchSource = r.searchSource.Profile(profile) + return r +} + +// Collapse adds field collapsing. +func (r *SearchRequest) Collapse(collapse *CollapseBuilder) *SearchRequest { + r.searchSource = r.searchSource.Collapse(collapse) + return r +} + +// AllowPartialSearchResults indicates if this request should allow partial +// results. (If method is not called, will default to the cluster level +// setting). +func (r *SearchRequest) AllowPartialSearchResults(allow bool) *SearchRequest { + r.allowPartialSearchResults = &allow + return r +} + +// BatchedReduceSize specifies the number of shard results that should be +// reduced at once on the coordinating node. This value should be used +// as a protection mechanism to reduce the memory overhead per search request +// if the potential number of shards in the request can be large. +func (r *SearchRequest) BatchedReduceSize(size int) *SearchRequest { + r.batchedReduceSize = &size + return r +} + +// MaxConcurrentShardRequests sets the number of shard requests that should +// be executed concurrently. This value should be used as a protection +// mechanism to reduce the number of shard requests fired per high level +// search request. Searches that hit the entire cluster can be throttled +// with this number to reduce the cluster load. The default grows with +// the number of nodes in the cluster but is at most 256. +func (r *SearchRequest) MaxConcurrentShardRequests(size int) *SearchRequest { + r.maxConcurrentShardRequests = &size + return r +} + +// PreFilterShardSize sets a threshold that enforces a pre-filter roundtrip +// to pre-filter search shards based on query rewriting if the number of +// shards the search request expands to exceeds the threshold. +// This filter roundtrip can limit the number of shards significantly if for +// instance a shard can not match any documents based on it's rewrite +// method ie. if date filters are mandatory to match but the shard +// bounds and the query are disjoint. The default is 128. +func (r *SearchRequest) PreFilterShardSize(size int) *SearchRequest { + r.preFilterShardSize = &size + return r +} + +// 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/7.0/search-multi-search.html +func (r *SearchRequest) header() interface{} { + h := make(map[string]interface{}) + if r.searchType != "" { + h["search_type"] = r.searchType + } + + switch len(r.indices) { + case 0: + case 1: + h["index"] = r.indices[0] + default: + h["indices"] = r.indices + } + + switch len(r.types) { + case 0: + case 1: + h["type"] = r.types[0] + default: + h["types"] = r.types + } + + if r.routing != nil && *r.routing != "" { + h["routing"] = *r.routing + } + if r.preference != nil && *r.preference != "" { + h["preference"] = *r.preference + } + if r.requestCache != nil { + h["request_cache"] = *r.requestCache + } + if r.ignoreUnavailable != nil { + h["ignore_unavailable"] = *r.ignoreUnavailable + } + if r.allowNoIndices != nil { + h["allow_no_indices"] = *r.allowNoIndices + } + if r.expandWildcards != "" { + h["expand_wildcards"] = r.expandWildcards + } + if v := r.allowPartialSearchResults; v != nil { + h["allow_partial_search_results"] = *v + } + if r.scroll != "" { + h["scroll"] = r.scroll + } + + return h +} + +// Body allows to access the search body of the request, as generated by the DSL. +// Notice that Body is read-only. You must not change the request body. +// +// 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/7.0/search-multi-search.html +func (r *SearchRequest) Body() (string, error) { + if r.source == nil { + // Default: No custom source specified + src, err := r.searchSource.Source() + if err != nil { + return "", err + } + body, err := json.Marshal(src) + if err != nil { + return "", err + } + return string(body), nil + } + switch t := r.source.(type) { + default: + body, err := json.Marshal(r.source) + if err != nil { + return "", err + } + return string(body), nil + case *SearchSource: + src, err := t.Source() + if err != nil { + return "", err + } + body, err := json.Marshal(src) + if err != nil { + return "", err + } + return string(body), nil + case json.RawMessage: + return string(t), nil + case *json.RawMessage: + return string(*t), nil + case string: + return t, nil + case *string: + if t != nil { + return *t, nil + } + return "{}", nil + } +} + +// source returns the search source. It is used by Reindex. +func (r *SearchRequest) sourceAsMap() (interface{}, error) { + if r.source == nil { + // Default: No custom source specified + return r.searchSource.Source() + } + switch t := r.source.(type) { + default: + body, err := json.Marshal(r.source) + if err != nil { + return "", err + } + return RawStringQuery(body), nil + case *SearchSource: + return t.Source() + case json.RawMessage: + return RawStringQuery(string(t)), nil + case *json.RawMessage: + return RawStringQuery(string(*t)), nil + case string: + return RawStringQuery(t), nil + case *string: + if t != nil { + return RawStringQuery(*t), nil + } + return RawStringQuery("{}"), nil + } +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_shards.go b/vendor/github.com/olivere/elastic/v7/search_shards.go similarity index 56% rename from vendor/gopkg.in/olivere/elastic.v6/search_shards.go rename to vendor/github.com/olivere/elastic/v7/search_shards.go index cd7383e..6e566ac 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_shards.go +++ b/vendor/github.com/olivere/elastic/v7/search_shards.go @@ -7,17 +7,25 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" + "time" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/search-shards.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-shards.html type SearchShardsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string routing string local *bool @@ -34,6 +42,46 @@ func NewSearchShardsService(client *Client) *SearchShardsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SearchShardsService) Pretty(pretty bool) *SearchShardsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SearchShardsService) Human(human bool) *SearchShardsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SearchShardsService) ErrorTrace(errorTrace bool) *SearchShardsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SearchShardsService) FilterPath(filterPath ...string) *SearchShardsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SearchShardsService) Header(name string, value string) *SearchShardsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SearchShardsService) Headers(headers http.Header) *SearchShardsService { + s.headers = headers + return s +} + // Index sets the names of the indices to restrict the results. func (s *SearchShardsService) Index(index ...string) *SearchShardsService { s.index = append(s.index, index...) @@ -59,12 +107,6 @@ func (s *SearchShardsService) Preference(preference string) *SearchShardsService 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 { @@ -99,8 +141,17 @@ func (s *SearchShardsService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.preference != "" { params.Set("preference", s.preference) @@ -150,9 +201,10 @@ func (s *SearchShardsService) Do(ctx context.Context) (*SearchShardsResponse, er // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -168,17 +220,39 @@ func (s *SearchShardsService) Do(ctx context.Context) (*SearchShardsResponse, er // 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"` + Nodes map[string]interface{} `json:"nodes"` + Indices map[string]interface{} `json:"indices"` + Shards [][]*SearchShardsResponseShardsInfo `json:"shards"` +} + +type SearchShardsResponseShardsInfo struct { + Index string `json:"index"` + Node string `json:"node"` + Primary bool `json:"primary"` + Shard uint `json:"shard"` + State string `json:"state"` + AllocationId *AllocationId `json:"allocation_id,omitempty"` + RelocatingNode string `json:"relocating_node"` + ExpectedShardSizeInBytes int64 `json:"expected_shard_size_in_bytes,omitempty"` + RecoverySource *RecoverySource `json:"recovery_source,omitempty"` + UnassignedInfo *UnassignedInfo `json:"unassigned_info,omitempty"` +} + +type RecoverySource struct { + Type string `json:"type"` + // TODO add missing fields here based on the Type +} + +type AllocationId struct { + Id string `json:"id"` + RelocationId string `json:"relocation_id,omitempty"` +} + +type UnassignedInfo struct { + Reason string `json:"reason"` + At *time.Time `json:"at,omitempty"` + FailedAttempts int `json:"failed_attempts,omitempty"` + Delayed bool `json:"delayed"` + Details string `json:"details,omitempty"` + AllocationStatus string `json:"allocation_status"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_source.go b/vendor/github.com/olivere/elastic/v7/search_source.go similarity index 72% rename from vendor/gopkg.in/olivere/elastic.v6/search_source.go rename to vendor/github.com/olivere/elastic/v7/search_source.go index e0deafb..ae2ae41 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_source.go +++ b/vendor/github.com/olivere/elastic/v7/search_source.go @@ -11,36 +11,37 @@ import ( // SearchSource enables users to build the search source. // It resembles the SearchSourceBuilder in Elasticsearch. type SearchSource struct { - query Query - postQuery Query - sliceQuery Query - from int - size int - explain *bool - version *bool - sorters []Sorter - trackScores *bool - trackTotalHits *bool - searchAfterSortValues []interface{} - minScore *float64 - timeout string - terminateAfter *int - storedFieldNames []string - docvalueFields []string - scriptFields []*ScriptField - fetchSourceContext *FetchSourceContext - aggregations map[string]Aggregation - highlight *Highlight + query Query // query + postQuery Query // post_filter + sliceQuery Query // slice + from int // from + size int // size + explain *bool // explain + version *bool // version + seqNoAndPrimaryTerm *bool // seq_no_primary_term + sorters []Sorter // sort + trackScores *bool // track_scores + trackTotalHits interface{} // track_total_hits + searchAfterSortValues []interface{} // search_after + minScore *float64 // min_score + timeout string // timeout + terminateAfter *int // terminate_after + storedFieldNames []string // stored_fields + docvalueFields DocvalueFields // docvalue_fields + scriptFields []*ScriptField // script_fields + fetchSourceContext *FetchSourceContext // _source + aggregations map[string]Aggregation // aggregations / aggs + highlight *Highlight // highlight globalSuggestText string - suggesters []Suggester - rescores []*Rescore + suggesters []Suggester // suggest + rescores []*Rescore // rescore defaultRescoreWindowSize *int - indexBoosts map[string]float64 - stats []string + indexBoosts IndexBoosts // indices_boost + stats []string // stats innerHits map[string]*InnerHit - collapse *CollapseBuilder - profile bool - // TODO extBuilders []SearchExtBuilder + collapse *CollapseBuilder // collapse + profile bool // profile + // TODO extBuilders []SearchExtBuilder // ext } // NewSearchSource initializes a new SearchSource. @@ -49,7 +50,6 @@ func NewSearchSource() *SearchSource { from: -1, size: -1, aggregations: make(map[string]Aggregation), - indexBoosts: make(map[string]float64), innerHits: make(map[string]*InnerHit), } } @@ -78,7 +78,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.2/search-request-scroll.html#sliced-scroll +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-scroll.html#sliced-scroll // for details. func (s *SearchSource) Slice(sliceQuery Query) *SearchSource { s.sliceQuery = sliceQuery @@ -117,6 +117,13 @@ func (s *SearchSource) Version(version bool) *SearchSource { return s } +// SeqNoAndPrimaryTerm indicates whether SearchHits should be returned with the +// sequence number and primary term of the last modification of the document. +func (s *SearchSource) SeqNoAndPrimaryTerm(enabled bool) *SearchSource { + s.seqNoAndPrimaryTerm = &enabled + return s +} + // Timeout controls how long a search is allowed to take, e.g. "1s" or "500ms". func (s *SearchSource) Timeout(timeout string) *SearchSource { s.timeout = timeout @@ -166,20 +173,20 @@ func (s *SearchSource) TrackScores(trackScores bool) *SearchSource { return s } -// TrackTotalHits indicates if the total hit count for the query should be tracked. -// Defaults to true. +// TrackTotalHits controls how the total number of hits should be tracked. +// Defaults to 10000 which will count the total hit accurately up to 10,000 hits. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/index-modules-index-sorting.html#early-terminate +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-track-total-hits.html // for details. -func (s *SearchSource) TrackTotalHits(trackTotalHits bool) *SearchSource { - s.trackTotalHits = &trackTotalHits +func (s *SearchSource) TrackTotalHits(trackTotalHits interface{}) *SearchSource { + s.trackTotalHits = trackTotalHits return s } // 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.2/search-request-search-after.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-search-after.html func (s *SearchSource) SearchAfter(sortValues ...interface{}) *SearchSource { s.searchAfterSortValues = append(s.searchAfterSortValues, sortValues...) return s @@ -254,10 +261,21 @@ func (s *SearchSource) FetchSourceContext(fetchSourceContext *FetchSourceContext return s } +// FetchSourceIncludeExclude specifies that _source should be returned +// with each hit, where "include" and "exclude" serve as a simple wildcard +// matcher that gets applied to its fields +// (e.g. include := []string{"obj1.*","obj2.*"}, exclude := []string{"description.*"}). +func (s *SearchSource) FetchSourceIncludeExclude(include, exclude []string) *SearchSource { + s.fetchSourceContext = NewFetchSourceContext(true). + Include(include...). + Exclude(exclude...) + return s +} + // NoStoredFields indicates that no fields should be loaded, resulting in only // id and type to be returned per field. func (s *SearchSource) NoStoredFields() *SearchSource { - s.storedFieldNames = nil + s.storedFieldNames = []string{} return s } @@ -279,13 +297,29 @@ func (s *SearchSource) StoredFields(storedFieldNames ...string) *SearchSource { // DocvalueField adds a single field to load from the field data cache // and return as part of the search request. func (s *SearchSource) DocvalueField(fieldDataField string) *SearchSource { - s.docvalueFields = append(s.docvalueFields, fieldDataField) + s.docvalueFields = append(s.docvalueFields, DocvalueField{Field: fieldDataField}) + return s +} + +// DocvalueField adds a single docvalue field to load from the field data cache +// and return as part of the search request. +func (s *SearchSource) DocvalueFieldWithFormat(fieldDataFieldWithFormat DocvalueField) *SearchSource { + s.docvalueFields = append(s.docvalueFields, fieldDataFieldWithFormat) return s } // DocvalueFields adds one or more fields to load from the field data cache // and return as part of the search request. func (s *SearchSource) DocvalueFields(docvalueFields ...string) *SearchSource { + for _, f := range docvalueFields { + s.docvalueFields = append(s.docvalueFields, DocvalueField{Field: f}) + } + return s +} + +// DocvalueFields adds one or more docvalue fields to load from the field data cache +// and return as part of the search request. +func (s *SearchSource) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *SearchSource { s.docvalueFields = append(s.docvalueFields, docvalueFields...) return s } @@ -305,7 +339,13 @@ func (s *SearchSource) ScriptFields(scriptFields ...*ScriptField) *SearchSource // IndexBoost sets the boost that a specific index will receive when the // query is executed against it. func (s *SearchSource) IndexBoost(index string, boost float64) *SearchSource { - s.indexBoosts[index] = boost + s.indexBoosts = append(s.indexBoosts, IndexBoost{Index: index, Boost: boost}) + return s +} + +// IndexBoosts sets the boosts for specific indices. +func (s *SearchSource) IndexBoosts(boosts ...IndexBoost) *SearchSource { + s.indexBoosts = append(s.indexBoosts, boosts...) return s } @@ -357,13 +397,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["post_filter"] = src } - if s.sliceQuery != nil { - src, err := s.sliceQuery.Source() - if err != nil { - return nil, err - } - source["slice"] = src - } if s.minScore != nil { source["min_score"] = *s.minScore } @@ -376,13 +409,6 @@ func (s *SearchSource) Source() (interface{}, error) { if s.profile { source["profile"] = s.profile } - if s.collapse != nil { - src, err := s.collapse.Source() - if err != nil { - return nil, err - } - source["collapse"] = src - } if s.fetchSourceContext != nil { src, err := s.fetchSourceContext.Source() if err != nil { @@ -390,7 +416,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["_source"] = src } - if s.storedFieldNames != nil { switch len(s.storedFieldNames) { case 1: @@ -399,11 +424,13 @@ func (s *SearchSource) Source() (interface{}, error) { source["stored_fields"] = s.storedFieldNames } } - if len(s.docvalueFields) > 0 { - source["docvalue_fields"] = s.docvalueFields + src, err := s.docvalueFields.Source() + if err != nil { + return nil, err + } + source["docvalue_fields"] = src } - if len(s.scriptFields) > 0 { sfmap := make(map[string]interface{}) for _, scriptField := range s.scriptFields { @@ -415,7 +442,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["script_fields"] = sfmap } - if len(s.sorters) > 0 { var sortarr []interface{} for _, sorter := range s.sorters { @@ -427,20 +453,29 @@ func (s *SearchSource) Source() (interface{}, error) { } source["sort"] = sortarr } - if v := s.trackScores; v != nil { source["track_scores"] = *v } if v := s.trackTotalHits; v != nil { - source["track_total_hits"] = *v + source["track_total_hits"] = v } if len(s.searchAfterSortValues) > 0 { source["search_after"] = s.searchAfterSortValues } + if s.sliceQuery != nil { + src, err := s.sliceQuery.Source() + if err != nil { + return nil, err + } + source["slice"] = src + } if len(s.indexBoosts) > 0 { - source["indices_boost"] = s.indexBoosts + src, err := s.indexBoosts.Source() + if err != nil { + return nil, err + } + source["indices_boost"] = src } - if len(s.aggregations) > 0 { aggsMap := make(map[string]interface{}) for name, aggregate := range s.aggregations { @@ -452,7 +487,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["aggregations"] = aggsMap } - if s.highlight != nil { src, err := s.highlight.Source() if err != nil { @@ -460,7 +494,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["highlight"] = src } - if len(s.suggesters) > 0 { suggesters := make(map[string]interface{}) for _, s := range s.suggesters { @@ -475,7 +508,6 @@ func (s *SearchSource) Source() (interface{}, error) { } source["suggest"] = suggesters } - if len(s.rescores) > 0 { // Strip empty rescores from request var rescores []*Rescore @@ -484,7 +516,6 @@ func (s *SearchSource) Source() (interface{}, error) { rescores = append(rescores, r) } } - if len(rescores) == 1 { rescores[0].defaultRescoreWindowSize = s.defaultRescoreWindowSize src, err := rescores[0].Source() @@ -505,10 +536,22 @@ func (s *SearchSource) Source() (interface{}, error) { source["rescore"] = slice } } - if len(s.stats) > 0 { source["stats"] = s.stats } + // TODO ext builders + + if s.collapse != nil { + src, err := s.collapse.Source() + if err != nil { + return nil, err + } + source["collapse"] = src + } + + if v := s.seqNoAndPrimaryTerm; v != nil { + source["seq_no_primary_term"] = *v + } if len(s.innerHits) > 0 { // Top-level inner hits @@ -556,3 +599,34 @@ func (s *SearchSource) Source() (interface{}, error) { return source, nil } + +// -- IndexBoosts -- + +// IndexBoost specifies an index by some boost factor. +type IndexBoost struct { + Index string + Boost float64 +} + +// Source generates a JSON-serializable output for IndexBoost. +func (b IndexBoost) Source() (interface{}, error) { + return map[string]interface{}{ + b.Index: b.Boost, + }, nil +} + +// IndexBoosts is a slice of IndexBoost entities. +type IndexBoosts []IndexBoost + +// Source generates a JSON-serializable output for IndexBoosts. +func (b IndexBoosts) Source() (interface{}, error) { + var boosts []interface{} + for _, ib := range b { + src, err := ib.Source() + if err != nil { + return nil, err + } + boosts = append(boosts, src) + } + return boosts, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_terms_lookup.go b/vendor/github.com/olivere/elastic/v7/search_terms_lookup.go similarity index 92% rename from vendor/gopkg.in/olivere/elastic.v6/search_terms_lookup.go rename to vendor/github.com/olivere/elastic/v7/search_terms_lookup.go index d3fac60..f5d6541 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/search_terms_lookup.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/query-dsl-terms-query.html#query-dsl-terms-lookup. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-terms-query.html#query-dsl-terms-lookup. type TermsLookup struct { index string typ string @@ -29,6 +29,8 @@ func (t *TermsLookup) Index(index string) *TermsLookup { } // Type name. +// +// Deprecated: Types are in the process of being removed. func (t *TermsLookup) Type(typ string) *TermsLookup { t.typ = typ return t diff --git a/vendor/gopkg.in/olivere/elastic.v6/snapshot_create.go b/vendor/github.com/olivere/elastic/v7/snapshot_create.go similarity index 66% rename from vendor/gopkg.in/olivere/elastic.v6/snapshot_create.go rename to vendor/github.com/olivere/elastic/v7/snapshot_create.go index 408ef70..0c3de06 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/snapshot_create.go +++ b/vendor/github.com/olivere/elastic/v7/snapshot_create.go @@ -8,16 +8,23 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" - "time" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) -// SnapshotCreateService is documented at https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-snapshots.html. +// SnapshotCreateService is documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html. type SnapshotCreateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + repository string snapshot string masterTimeout string @@ -33,6 +40,46 @@ func NewSnapshotCreateService(client *Client) *SnapshotCreateService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotCreateService) Pretty(pretty bool) *SnapshotCreateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotCreateService) Human(human bool) *SnapshotCreateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotCreateService) ErrorTrace(errorTrace bool) *SnapshotCreateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotCreateService) FilterPath(filterPath ...string) *SnapshotCreateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotCreateService) Header(name string, value string) *SnapshotCreateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotCreateService) Headers(headers http.Header) *SnapshotCreateService { + s.headers = headers + return s +} + // Repository is the repository name. func (s *SnapshotCreateService) Repository(repository string) *SnapshotCreateService { s.repository = repository @@ -57,12 +104,6 @@ func (s *SnapshotCreateService) WaitForCompletion(waitForCompletion bool) *Snaps return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *SnapshotCreateService) Pretty(pretty bool) *SnapshotCreateService { - s.pretty = pretty - return s -} - // BodyJson is documented as: The snapshot definition. func (s *SnapshotCreateService) BodyJson(body interface{}) *SnapshotCreateService { s.bodyJson = body @@ -88,14 +129,23 @@ func (s *SnapshotCreateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) } - if s.waitForCompletion != nil { - params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion)) + if v := s.waitForCompletion; v != nil { + params.Set("wait_for_completion", fmt.Sprint(*v)) } return path, params, nil } @@ -138,10 +188,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -172,20 +223,5 @@ type SnapshotCreateResponse struct { Accepted *bool `json:"accepted"` // Snapshot is available when waitForCompletion is true. - Snapshot *struct { - Snapshot string `json:"snapshot"` - UUID string `json:"uuid"` - VersionID int `json:"version_id"` - Version string `json:"version"` - Indices []string `json:"indices"` - State string `json:"state"` - Reason string `json:"reason"` - StartTime time.Time `json:"start_time"` - StartTimeInMillis int64 `json:"start_time_in_millis"` - EndTime time.Time `json:"end_time"` - EndTimeInMillis int64 `json:"end_time_in_millis"` - DurationInMillis int64 `json:"duration_in_millis"` - Failures []SnapshotShardFailure `json:"failures"` - Shards shardsInfo `json:"shards"` - } `json:"snapshot"` + Snapshot *Snapshot `json:"snapshot"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/snapshot_create_repository.go b/vendor/github.com/olivere/elastic/v7/snapshot_create_repository.go similarity index 69% rename from vendor/gopkg.in/olivere/elastic.v6/snapshot_create_repository.go rename to vendor/github.com/olivere/elastic/v7/snapshot_create_repository.go index bbeb69f..5976b2a 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/snapshot_create_repository.go +++ b/vendor/github.com/olivere/elastic/v7/snapshot_create_repository.go @@ -8,17 +8,25 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // SnapshotCreateRepositoryService creates a snapshot repository. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-snapshots.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html // for details. type SnapshotCreateRepositoryService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + repository string masterTimeout string timeout string @@ -36,6 +44,46 @@ func NewSnapshotCreateRepositoryService(client *Client) *SnapshotCreateRepositor } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotCreateRepositoryService) Pretty(pretty bool) *SnapshotCreateRepositoryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotCreateRepositoryService) Human(human bool) *SnapshotCreateRepositoryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotCreateRepositoryService) ErrorTrace(errorTrace bool) *SnapshotCreateRepositoryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotCreateRepositoryService) FilterPath(filterPath ...string) *SnapshotCreateRepositoryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotCreateRepositoryService) Header(name string, value string) *SnapshotCreateRepositoryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotCreateRepositoryService) Headers(headers http.Header) *SnapshotCreateRepositoryService { + s.headers = headers + return s +} + // Repository is the repository name. func (s *SnapshotCreateRepositoryService) Repository(repository string) *SnapshotCreateRepositoryService { s.repository = repository @@ -60,12 +108,6 @@ func (s *SnapshotCreateRepositoryService) Verify(verify bool) *SnapshotCreateRep return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *SnapshotCreateRepositoryService) Pretty(pretty bool) *SnapshotCreateRepositoryService { - s.pretty = pretty - return s -} - // Type sets the snapshot repository type, e.g. "fs". func (s *SnapshotCreateRepositoryService) Type(typ string) *SnapshotCreateRepositoryService { s.typ = typ @@ -111,8 +153,17 @@ func (s *SnapshotCreateRepositoryService) buildURL() (string, url.Values, error) // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -120,8 +171,8 @@ func (s *SnapshotCreateRepositoryService) buildURL() (string, url.Values, error) if s.timeout != "" { params.Set("timeout", s.timeout) } - if s.verify != nil { - params.Set("verify", fmt.Sprintf("%v", *s.verify)) + if v := s.verify; v != nil { + params.Set("verify", fmt.Sprint(*v)) } return path, params, nil } @@ -150,7 +201,7 @@ func (s *SnapshotCreateRepositoryService) Validate() error { if s.repository == "" { invalid = append(invalid, "Repository") } - if s.bodyString == "" && s.bodyJson == nil { + if s.bodyString == "" && s.bodyJson == nil && len(s.settings) == 0 { invalid = append(invalid, "BodyJson") } if len(invalid) > 0 { @@ -180,10 +231,11 @@ 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, + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/snapshot_delete.go b/vendor/github.com/olivere/elastic/v7/snapshot_delete.go new file mode 100644 index 0000000..74cf09b --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/snapshot_delete.go @@ -0,0 +1,154 @@ +// 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/http" + "net/url" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// SnapshotDeleteService deletes a snapshot from a snapshot repository. +// It is documented at +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html. +type SnapshotDeleteService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + repository string + snapshot string +} + +// NewSnapshotDeleteService creates a new SnapshotDeleteService. +func NewSnapshotDeleteService(client *Client) *SnapshotDeleteService { + return &SnapshotDeleteService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotDeleteService) Pretty(pretty bool) *SnapshotDeleteService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotDeleteService) Human(human bool) *SnapshotDeleteService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotDeleteService) ErrorTrace(errorTrace bool) *SnapshotDeleteService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotDeleteService) FilterPath(filterPath ...string) *SnapshotDeleteService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotDeleteService) Header(name string, value string) *SnapshotDeleteService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotDeleteService) Headers(headers http.Header) *SnapshotDeleteService { + s.headers = headers + return s +} + +// Repository is the repository name. +func (s *SnapshotDeleteService) Repository(repository string) *SnapshotDeleteService { + s.repository = repository + return s +} + +// Snapshot is the snapshot name. +func (s *SnapshotDeleteService) Snapshot(snapshot string) *SnapshotDeleteService { + s.snapshot = snapshot + return s +} + +// buildURL builds the URL for the operation. +func (s *SnapshotDeleteService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_snapshot/{repository}/{snapshot}", map[string]string{ + "repository": s.repository, + "snapshot": s.snapshot, + }) + if err != nil { + return "", url.Values{}, err + } + return path, url.Values{}, nil +} + +// Validate checks if the operation is valid. +func (s *SnapshotDeleteService) Validate() error { + var invalid []string + if s.repository == "" { + invalid = append(invalid, "Repository") + } + if s.snapshot == "" { + invalid = append(invalid, "Snapshot") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *SnapshotDeleteService) Do(ctx context.Context) (*SnapshotDeleteResponse, 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, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(SnapshotDeleteResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// SnapshotDeleteResponse is the response of SnapshotDeleteService.Do. +type SnapshotDeleteResponse struct { + Acknowledged bool `json:"acknowledged"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/snapshot_delete_repository.go b/vendor/github.com/olivere/elastic/v7/snapshot_delete_repository.go similarity index 60% rename from vendor/gopkg.in/olivere/elastic.v6/snapshot_delete_repository.go rename to vendor/github.com/olivere/elastic/v7/snapshot_delete_repository.go index 5a16a5d..15b755c 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/snapshot_delete_repository.go +++ b/vendor/github.com/olivere/elastic/v7/snapshot_delete_repository.go @@ -8,18 +8,25 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // SnapshotDeleteRepositoryService deletes a snapshot repository. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-snapshots.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html // for details. type SnapshotDeleteRepositoryService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + repository []string masterTimeout string timeout string @@ -33,6 +40,46 @@ func NewSnapshotDeleteRepositoryService(client *Client) *SnapshotDeleteRepositor } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotDeleteRepositoryService) Pretty(pretty bool) *SnapshotDeleteRepositoryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotDeleteRepositoryService) Human(human bool) *SnapshotDeleteRepositoryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotDeleteRepositoryService) ErrorTrace(errorTrace bool) *SnapshotDeleteRepositoryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotDeleteRepositoryService) FilterPath(filterPath ...string) *SnapshotDeleteRepositoryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotDeleteRepositoryService) Header(name string, value string) *SnapshotDeleteRepositoryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotDeleteRepositoryService) Headers(headers http.Header) *SnapshotDeleteRepositoryService { + s.headers = headers + return s +} + // Repository is the list of repository names. func (s *SnapshotDeleteRepositoryService) Repository(repositories ...string) *SnapshotDeleteRepositoryService { s.repository = append(s.repository, repositories...) @@ -51,12 +98,6 @@ func (s *SnapshotDeleteRepositoryService) Timeout(timeout string) *SnapshotDelet return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *SnapshotDeleteRepositoryService) Pretty(pretty bool) *SnapshotDeleteRepositoryService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *SnapshotDeleteRepositoryService) buildURL() (string, url.Values, error) { // Build URL @@ -69,8 +110,17 @@ func (s *SnapshotDeleteRepositoryService) buildURL() (string, url.Values, error) // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -108,9 +158,10 @@ func (s *SnapshotDeleteRepositoryService) Do(ctx context.Context) (*SnapshotDele // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "DELETE", - Path: path, - Params: params, + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/snapshot_get.go b/vendor/github.com/olivere/elastic/v7/snapshot_get.go new file mode 100644 index 0000000..02cf99e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/snapshot_get.go @@ -0,0 +1,225 @@ +// 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/http" + "net/url" + "strings" + "time" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// SnapshotGetService lists the snapshots on a repository +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html +// for details. +type SnapshotGetService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + repository string + snapshot []string + masterTimeout string + ignoreUnavailable *bool + verbose *bool +} + +// NewSnapshotGetService creates a new SnapshotGetService. +func NewSnapshotGetService(client *Client) *SnapshotGetService { + return &SnapshotGetService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotGetService) Pretty(pretty bool) *SnapshotGetService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotGetService) Human(human bool) *SnapshotGetService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotGetService) ErrorTrace(errorTrace bool) *SnapshotGetService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotGetService) FilterPath(filterPath ...string) *SnapshotGetService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotGetService) Header(name string, value string) *SnapshotGetService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotGetService) Headers(headers http.Header) *SnapshotGetService { + s.headers = headers + return s +} + +// Repository is the repository name. +func (s *SnapshotGetService) Repository(repository string) *SnapshotGetService { + s.repository = repository + return s +} + +// Snapshot is the list of snapshot names. If not set, defaults to all snapshots. +func (s *SnapshotGetService) Snapshot(snapshots ...string) *SnapshotGetService { + s.snapshot = append(s.snapshot, snapshots...) + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *SnapshotGetService) MasterTimeout(masterTimeout string) *SnapshotGetService { + s.masterTimeout = masterTimeout + return s +} + +// IgnoreUnavailable specifies whether to ignore unavailable snapshots, defaults to false +func (s *SnapshotGetService) IgnoreUnavailable(ignoreUnavailable bool) *SnapshotGetService { + s.ignoreUnavailable = &ignoreUnavailable + return s +} + +// Verbose specifies whether to show verbose snapshot info or only show the basic info found in the repository index blob +func (s *SnapshotGetService) Verbose(verbose bool) *SnapshotGetService { + s.verbose = &verbose + return s +} + +// buildURL builds the URL for the operation. +func (s *SnapshotGetService) buildURL() (string, url.Values, error) { + // Build URL + var err error + var path string + if len(s.snapshot) > 0 { + path, err = uritemplates.Expand("/_snapshot/{repository}/{snapshot}", map[string]string{ + "repository": s.repository, + "snapshot": strings.Join(s.snapshot, ","), + }) + } else { + path, err = uritemplates.Expand("/_snapshot/{repository}/_all", map[string]string{ + "repository": s.repository, + }) + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) + } + if v := s.verbose; v != nil { + params.Set("verbose", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *SnapshotGetService) Validate() error { + var invalid []string + if s.repository == "" { + invalid = append(invalid, "Repository") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *SnapshotGetService) Do(ctx context.Context) (*SnapshotGetResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(SnapshotGetResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// SnapshotGetResponse is the response of SnapshotGetService.Do. +type SnapshotGetResponse struct { + Snapshots []*Snapshot `json:"snapshots"` +} + +// Snapshot contains all information about a single snapshot +type Snapshot struct { + Snapshot string `json:"snapshot"` + UUID string `json:"uuid"` + VersionID int `json:"version_id"` + Version string `json:"version"` + Indices []string `json:"indices"` + State string `json:"state"` + Reason string `json:"reason"` + StartTime time.Time `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + EndTime time.Time `json:"end_time"` + EndTimeInMillis int64 `json:"end_time_in_millis"` + DurationInMillis int64 `json:"duration_in_millis"` + Failures []SnapshotShardFailure `json:"failures"` + Shards *ShardsInfo `json:"shards"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/snapshot_get_repository.go b/vendor/github.com/olivere/elastic/v7/snapshot_get_repository.go similarity index 60% rename from vendor/gopkg.in/olivere/elastic.v6/snapshot_get_repository.go rename to vendor/github.com/olivere/elastic/v7/snapshot_get_repository.go index b1794c1..2860356 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/snapshot_get_repository.go +++ b/vendor/github.com/olivere/elastic/v7/snapshot_get_repository.go @@ -8,18 +8,25 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // SnapshotGetRepositoryService reads a snapshot repository. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-snapshots.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html // for details. type SnapshotGetRepositoryService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + repository []string local *bool masterTimeout string @@ -33,6 +40,46 @@ func NewSnapshotGetRepositoryService(client *Client) *SnapshotGetRepositoryServi } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotGetRepositoryService) Pretty(pretty bool) *SnapshotGetRepositoryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotGetRepositoryService) Human(human bool) *SnapshotGetRepositoryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotGetRepositoryService) ErrorTrace(errorTrace bool) *SnapshotGetRepositoryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotGetRepositoryService) FilterPath(filterPath ...string) *SnapshotGetRepositoryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotGetRepositoryService) Header(name string, value string) *SnapshotGetRepositoryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotGetRepositoryService) Headers(headers http.Header) *SnapshotGetRepositoryService { + s.headers = headers + return s +} + // Repository is the list of repository names. func (s *SnapshotGetRepositoryService) Repository(repositories ...string) *SnapshotGetRepositoryService { s.repository = append(s.repository, repositories...) @@ -51,12 +98,6 @@ func (s *SnapshotGetRepositoryService) MasterTimeout(masterTimeout string) *Snap return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *SnapshotGetRepositoryService) Pretty(pretty bool) *SnapshotGetRepositoryService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *SnapshotGetRepositoryService) buildURL() (string, url.Values, error) { // Build URL @@ -75,11 +116,20 @@ func (s *SnapshotGetRepositoryService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } - if s.local != nil { - params.Set("local", fmt.Sprintf("%v", *s.local)) + if v := s.local; v != nil { + params.Set("local", fmt.Sprint(*v)) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -107,9 +157,10 @@ func (s *SnapshotGetRepositoryService) Do(ctx context.Context) (SnapshotGetRepos // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/snapshot_restore.go b/vendor/github.com/olivere/elastic/v7/snapshot_restore.go new file mode 100644 index 0000000..1d0b8c0 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/snapshot_restore.go @@ -0,0 +1,298 @@ +// 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// SnapshotRestoreService restores a snapshot from a snapshot repository. +// +// It is documented at +// https://www.elastic.co/guide/en/elasticsearch/reference/7.1/modules-snapshots.html#_restore. +type SnapshotRestoreService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + repository string + snapshot string + masterTimeout string + waitForCompletion *bool + ignoreUnavailable *bool + partial *bool + includeAliases *bool + includeGlobalState *bool + bodyString string + renamePattern string + renameReplacement string + indices []string + indexSettings map[string]interface{} +} + +// NewSnapshotCreateService creates a new SnapshotRestoreService. +func NewSnapshotRestoreService(client *Client) *SnapshotRestoreService { + return &SnapshotRestoreService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotRestoreService) Pretty(pretty bool) *SnapshotRestoreService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotRestoreService) Human(human bool) *SnapshotRestoreService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotRestoreService) ErrorTrace(errorTrace bool) *SnapshotRestoreService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotRestoreService) FilterPath(filterPath ...string) *SnapshotRestoreService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotRestoreService) Header(name string, value string) *SnapshotRestoreService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotRestoreService) Headers(headers http.Header) *SnapshotRestoreService { + s.headers = headers + return s +} + +// Repository name. +func (s *SnapshotRestoreService) Repository(repository string) *SnapshotRestoreService { + s.repository = repository + return s +} + +// Snapshot name. +func (s *SnapshotRestoreService) Snapshot(snapshot string) *SnapshotRestoreService { + s.snapshot = snapshot + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *SnapshotRestoreService) MasterTimeout(masterTimeout string) *SnapshotRestoreService { + s.masterTimeout = masterTimeout + return s +} + +// WaitForCompletion indicates whether this request should wait until the operation has +// completed before returning. +func (s *SnapshotRestoreService) WaitForCompletion(waitForCompletion bool) *SnapshotRestoreService { + s.waitForCompletion = &waitForCompletion + return s +} + +// Indices sets the name of the indices that should be restored from the snapshot. +func (s *SnapshotRestoreService) Indices(indices ...string) *SnapshotRestoreService { + s.indices = indices + return s +} + +// IncludeGlobalState allows the global cluster state to be restored, defaults to false. +func (s *SnapshotRestoreService) IncludeGlobalState(includeGlobalState bool) *SnapshotRestoreService { + s.includeGlobalState = &includeGlobalState + return s +} + +// RenamePattern helps rename indices on restore using regular expressions. +func (s *SnapshotRestoreService) RenamePattern(renamePattern string) *SnapshotRestoreService { + s.renamePattern = renamePattern + return s +} + +// RenameReplacement as RenamePattern, helps rename indices on restore using regular expressions. +func (s *SnapshotRestoreService) RenameReplacement(renameReplacement string) *SnapshotRestoreService { + s.renameReplacement = renameReplacement + return s +} + +// Partial indicates whether to restore indices that where partially snapshoted, defaults to false. +func (s *SnapshotRestoreService) Partial(partial bool) *SnapshotRestoreService { + s.partial = &partial + return s +} + +// BodyString allows the user to specify the body of the HTTP request manually. +func (s *SnapshotRestoreService) BodyString(body string) *SnapshotRestoreService { + s.bodyString = body + return s +} + +// IndexSettings sets the settings to be overwritten during the restore process +func (s *SnapshotRestoreService) IndexSettings(indexSettings map[string]interface{}) *SnapshotRestoreService { + s.indexSettings = indexSettings + return s +} + +// IncludeAliases flags whether indices should be restored with their respective aliases, +// defaults to false. +func (s *SnapshotRestoreService) IncludeAliases(includeAliases bool) *SnapshotRestoreService { + s.includeAliases = &includeAliases + return s +} + +// IgnoreUnavailable specifies whether to ignore unavailable snapshots, defaults to false. +func (s *SnapshotRestoreService) IgnoreUnavailable(ignoreUnavailable bool) *SnapshotRestoreService { + s.ignoreUnavailable = &ignoreUnavailable + return s +} + +// Do executes the operation. +func (s *SnapshotRestoreService) Do(ctx context.Context) (*SnapshotRestoreResponse, error) { + if err := s.Validate(); err != nil { + return nil, err + } + path, params, err := s.buildURL() + if err != nil { + return nil, err + } + + var body interface{} + if len(s.bodyString) > 0 { + body = s.bodyString + } else { + body = s.buildBody() + } + + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + ret := new(SnapshotRestoreResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// Validate checks if the operation is valid. +func (s *SnapshotRestoreService) Validate() error { + var invalid []string + if s.repository == "" { + invalid = append(invalid, "Repository") + } + if s.snapshot == "" { + invalid = append(invalid, "Snapshot") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +func (s *SnapshotRestoreService) buildURL() (string, url.Values, error) { + path, err := uritemplates.Expand("/_snapshot/{repository}/{snapshot}/_restore", map[string]string{ + "snapshot": s.snapshot, + "repository": s.repository, + }) + if err != nil { + return "", url.Values{}, err + } + + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.waitForCompletion; v != nil { + params.Set("wait_for_completion", fmt.Sprint(*v)) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) + } + return path, params, nil +} + +func (s *SnapshotRestoreService) buildBody() interface{} { + body := map[string]interface{}{} + + if s.includeGlobalState != nil { + body["include_global_state"] = *s.includeGlobalState + } + if s.partial != nil { + body["partial"] = *s.partial + } + if s.includeAliases != nil { + body["include_aliases"] = *s.includeAliases + } + if len(s.indices) > 0 { + body["indices"] = strings.Join(s.indices, ",") + } + if len(s.renamePattern) > 0 { + body["rename_pattern"] = s.renamePattern + } + if len(s.renamePattern) > 0 { + body["rename_replacement"] = s.renameReplacement + } + if len(s.indexSettings) > 0 { + body["index_settings"] = s.indexSettings + } + return body +} + +// SnapshotRestoreResponse represents the response for SnapshotRestoreService.Do +type SnapshotRestoreResponse struct { + // Accepted indicates whether the request was accepted by Elasticsearch. + Accepted *bool `json:"accepted"` + + // Snapshot information. + Snapshot *RestoreInfo `json:"snapshot"` +} + +// RestoreInfo represents information about the restored snapshot. +type RestoreInfo struct { + Snapshot string `json:"snapshot"` + Indices []string `json:"indices"` + Shards ShardsInfo `json:"shards"` +} diff --git a/vendor/github.com/olivere/elastic/v7/snapshot_status.go b/vendor/github.com/olivere/elastic/v7/snapshot_status.go new file mode 100644 index 0000000..c03ca37 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/snapshot_status.go @@ -0,0 +1,258 @@ +// 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// SnapshotStatusService returns information about the status of a snapshot. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/modules-snapshots.html +// for details. +type SnapshotStatusService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + repository string + snapshot []string + masterTimeout string + ignoreUnavailable *bool +} + +// NewSnapshotStatusService creates a new SnapshotStatusService. +func NewSnapshotStatusService(client *Client) *SnapshotStatusService { + return &SnapshotStatusService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotStatusService) Pretty(pretty bool) *SnapshotStatusService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotStatusService) Human(human bool) *SnapshotStatusService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotStatusService) ErrorTrace(errorTrace bool) *SnapshotStatusService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotStatusService) FilterPath(filterPath ...string) *SnapshotStatusService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotStatusService) Header(name string, value string) *SnapshotStatusService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotStatusService) Headers(headers http.Header) *SnapshotStatusService { + s.headers = headers + return s +} + +// Repository is the repository name. +func (s *SnapshotStatusService) Repository(repository string) *SnapshotStatusService { + s.repository = repository + return s +} + +// Snapshot is the list of snapshot names. If not set, defaults to all snapshots. +func (s *SnapshotStatusService) Snapshot(snapshots ...string) *SnapshotStatusService { + s.snapshot = append(s.snapshot, snapshots...) + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *SnapshotStatusService) MasterTimeout(masterTimeout string) *SnapshotStatusService { + s.masterTimeout = masterTimeout + return s +} + +// buildURL builds the URL for the operation. +func (s *SnapshotStatusService) buildURL() (string, url.Values, error) { + var err error + var path string + + if s.repository != "" { + if len(s.snapshot) > 0 { + path, err = uritemplates.Expand("/_snapshot/{repository}/{snapshot}/_status", map[string]string{ + "repository": s.repository, + "snapshot": strings.Join(s.snapshot, ","), + }) + } else { + path, err = uritemplates.Expand("/_snapshot/{repository}/_status", map[string]string{ + "repository": s.repository, + }) + } + } else { + path, err = uritemplates.Expand("/_snapshot/_status", nil) + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +// +// Validation only fails if snapshot names were provided but no repository was +// provided. +func (s *SnapshotStatusService) Validate() error { + if len(s.snapshot) > 0 && s.repository == "" { + return fmt.Errorf("snapshots were specified but repository is missing") + } + return nil +} + +// Do executes the operation. +func (s *SnapshotStatusService) Do(ctx context.Context) (*SnapshotStatusResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(SnapshotStatusResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +type SnapshotStatusResponse struct { + Snapshots []SnapshotStatus `json:"snapshots"` +} + +type SnapshotStatus struct { + Snapshot string `json:"snapshot"` + Repository string `json:"repository"` + UUID string `json:"uuid"` + State string `json:"state"` + IncludeGlobalState bool `json:"include_global_state"` + ShardsStats SnapshotShardsStats `json:"shards_stats"` + Stats SnapshotStats `json:"stats"` + Indices map[string]SnapshotIndexStatus `json:"indices"` +} + +type SnapshotShardsStats struct { + Initializing int `json:"initializing"` + Started int `json:"started"` + Finalizing int `json:"finalizing"` + Done int `json:"done"` + Failed int `json:"failed"` + Total int `json:"total"` +} + +type SnapshotStats struct { + Incremental struct { + FileCount int `json:"file_count"` + Size string `json:"size"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"incremental"` + + Processed struct { + FileCount int `json:"file_count"` + Size string `json:"size"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"processed"` + + Total struct { + FileCount int `json:"file_count"` + Size string `json:"size"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"total"` + + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + + Time string `json:"time"` + TimeInMillis int64 `json:"time_in_millis"` + + NumberOfFiles int `json:"number_of_files"` + ProcessedFiles int `json:"processed_files"` + + TotalSize string `json:"total_size"` + TotalSizeInBytes int64 `json:"total_size_in_bytes"` +} + +type SnapshotIndexStatus struct { + ShardsStats SnapshotShardsStats `json:"shards_stats"` + Stats SnapshotStats `json:"stats"` + Shards map[string]SnapshotIndexShardStatus `json:"shards"` +} + +type SnapshotIndexShardStatus struct { + Stage string `json:"stage"` // initializing, started, finalize, done, or failed + Stats SnapshotStats `json:"stats"` + Node string `json:"node"` + Reason string `json:"reason"` // reason for failure +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/snapshot_verify_repository.go b/vendor/github.com/olivere/elastic/v7/snapshot_verify_repository.go similarity index 59% rename from vendor/gopkg.in/olivere/elastic.v6/snapshot_verify_repository.go rename to vendor/github.com/olivere/elastic/v7/snapshot_verify_repository.go index fb88206..ca8eab2 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/snapshot_verify_repository.go +++ b/vendor/github.com/olivere/elastic/v7/snapshot_verify_repository.go @@ -8,17 +8,25 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" + "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // SnapshotVerifyRepositoryService verifies a snapshop repository. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-snapshots.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-snapshots.html // for details. type SnapshotVerifyRepositoryService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + repository string masterTimeout string timeout string @@ -31,6 +39,46 @@ func NewSnapshotVerifyRepositoryService(client *Client) *SnapshotVerifyRepositor } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *SnapshotVerifyRepositoryService) Pretty(pretty bool) *SnapshotVerifyRepositoryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *SnapshotVerifyRepositoryService) Human(human bool) *SnapshotVerifyRepositoryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *SnapshotVerifyRepositoryService) ErrorTrace(errorTrace bool) *SnapshotVerifyRepositoryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *SnapshotVerifyRepositoryService) FilterPath(filterPath ...string) *SnapshotVerifyRepositoryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *SnapshotVerifyRepositoryService) Header(name string, value string) *SnapshotVerifyRepositoryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *SnapshotVerifyRepositoryService) Headers(headers http.Header) *SnapshotVerifyRepositoryService { + s.headers = headers + return s +} + // Repository specifies the repository name. func (s *SnapshotVerifyRepositoryService) Repository(repository string) *SnapshotVerifyRepositoryService { s.repository = repository @@ -49,12 +97,6 @@ func (s *SnapshotVerifyRepositoryService) Timeout(timeout string) *SnapshotVerif return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *SnapshotVerifyRepositoryService) Pretty(pretty bool) *SnapshotVerifyRepositoryService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *SnapshotVerifyRepositoryService) buildURL() (string, url.Values, error) { // Build URL @@ -67,8 +109,17 @@ func (s *SnapshotVerifyRepositoryService) buildURL() (string, url.Values, error) // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.masterTimeout != "" { params.Set("master_timeout", s.masterTimeout) @@ -106,9 +157,10 @@ func (s *SnapshotVerifyRepositoryService) Do(ctx context.Context) (*SnapshotVeri // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/gopkg.in/olivere/elastic.v6/sort.go b/vendor/github.com/olivere/elastic/v7/sort.go similarity index 85% rename from vendor/gopkg.in/olivere/elastic.v6/sort.go rename to vendor/github.com/olivere/elastic/v7/sort.go index 064d05e..60cc0a1 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/sort.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-request-sort.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-sort.html. type Sorter interface { Source() (interface{}, error) } @@ -25,9 +25,12 @@ type SortInfo struct { IgnoreUnmapped *bool UnmappedType string SortMode string - NestedFilter Query - NestedPath string - NestedSort *NestedSort // available in 6.1 or later + NestedFilter Query // deprecated in 6.1 and replaced by Filter + Filter Query + NestedPath string // deprecated in 6.1 and replaced by Path + Path string + NestedSort *NestedSort // deprecated in 6.1 and replaced by Nested + Nested *NestedSort } func (info SortInfo) Source() (interface{}, error) { @@ -49,17 +52,31 @@ func (info SortInfo) Source() (interface{}, error) { if info.SortMode != "" { prop["mode"] = info.SortMode } - if info.NestedFilter != nil { + if info.Filter != nil { + src, err := info.Filter.Source() + if err != nil { + return nil, err + } + prop["filter"] = src + } else if info.NestedFilter != nil { src, err := info.NestedFilter.Source() if err != nil { return nil, err } - prop["nested_filter"] = src + prop["nested_filter"] = src // deprecated in 6.1 } - if info.NestedPath != "" { - prop["nested_path"] = info.NestedPath + if info.Path != "" { + prop["path"] = info.Path + } else if info.NestedPath != "" { + prop["nested_path"] = info.NestedPath // deprecated in 6.1 } - if info.NestedSort != nil { + if info.Nested != nil { + src, err := info.Nested.Source() + if err != nil { + return nil, err + } + prop["nested"] = src + } else if info.NestedSort != nil { src, err := info.NestedSort.Source() if err != nil { return nil, err @@ -74,7 +91,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.2/search-request-scroll.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-scroll.html. // // Example: // ss := elastic.NewSearchSource() @@ -142,9 +159,9 @@ type FieldSort struct { missing interface{} unmappedType *string sortMode *string - nestedFilter Query - nestedPath *string - nestedSort *NestedSort + filter Query + path *string + nested *NestedSort } // NewFieldSort creates a new FieldSort. @@ -204,22 +221,45 @@ func (s *FieldSort) SortMode(sortMode string) *FieldSort { // NestedFilter sets a filter that nested objects should match with // in order to be taken into account for sorting. +// Deprecated: Use Filter instead. func (s *FieldSort) NestedFilter(nestedFilter Query) *FieldSort { - s.nestedFilter = nestedFilter + s.filter = nestedFilter + return s +} + +// Filter sets a filter that nested objects should match with +// in order to be taken into account for sorting. +func (s *FieldSort) Filter(filter Query) *FieldSort { + s.filter = filter return s } // NestedPath is used if sorting occurs on a field that is inside a // nested object. +// Deprecated: Use Path instead. func (s *FieldSort) NestedPath(nestedPath string) *FieldSort { - s.nestedPath = &nestedPath + s.path = &nestedPath + return s +} + +// Path is used if sorting occurs on a field that is inside a +// nested object. +func (s *FieldSort) Path(path string) *FieldSort { + s.path = &path return s } // NestedSort is available starting with 6.1 and will replace NestedFilter // and NestedPath. +// Deprecated: Use Nested instead. func (s *FieldSort) NestedSort(nestedSort *NestedSort) *FieldSort { - s.nestedSort = nestedSort + s.nested = nestedSort + return s +} + +// Nested is available starting with 6.1 and will replace Filter and Path. +func (s *FieldSort) Nested(nested *NestedSort) *FieldSort { + s.nested = nested return s } @@ -242,18 +282,18 @@ func (s *FieldSort) Source() (interface{}, error) { if s.sortMode != nil { x["mode"] = *s.sortMode } - if s.nestedFilter != nil { - src, err := s.nestedFilter.Source() + if s.filter != nil { + src, err := s.filter.Source() if err != nil { return nil, err } - x["nested_filter"] = src + x["filter"] = src } - if s.nestedPath != nil { - x["nested_path"] = *s.nestedPath + if s.path != nil { + x["path"] = *s.path } - if s.nestedSort != nil { - src, err := s.nestedSort.Source() + if s.nested != nil { + src, err := s.nested.Source() if err != nil { return nil, err } @@ -265,7 +305,7 @@ func (s *FieldSort) Source() (interface{}, error) { // -- GeoDistanceSort -- // GeoDistanceSort allows for sorting by geographic distance. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-sort.html#_geo_distance_sorting. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-sort.html#_geo_distance_sorting. type GeoDistanceSort struct { Sorter fieldName string @@ -331,7 +371,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.2/common-options.html#distance-units +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/common-options.html#distance-units // for details. func (s *GeoDistanceSort) Unit(unit string) *GeoDistanceSort { s.unit = unit @@ -344,7 +384,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.2/search-request-sort.html#geo-sorting +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-sort.html#geo-sorting // for details. func (s *GeoDistanceSort) DistanceType(distanceType string) *GeoDistanceSort { s.distanceType = &distanceType @@ -434,7 +474,7 @@ func (s *GeoDistanceSort) Source() (interface{}, error) { // -- ScriptSort -- // ScriptSort sorts by a custom script. See -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/modules-scripting.html#modules-scripting +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/modules-scripting.html#modules-scripting // for details about scripting. type ScriptSort struct { Sorter diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggest_field.go b/vendor/github.com/olivere/elastic/v7/suggest_field.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/suggest_field.go rename to vendor/github.com/olivere/elastic/v7/suggest_field.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester.go b/vendor/github.com/olivere/elastic/v7/suggester.go similarity index 100% rename from vendor/gopkg.in/olivere/elastic.v6/suggester.go rename to vendor/github.com/olivere/elastic/v7/suggester.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_completion.go b/vendor/github.com/olivere/elastic/v7/suggester_completion.go similarity index 95% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_completion.go rename to vendor/github.com/olivere/elastic/v7/suggester_completion.go index 858fda1..668f0c2 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_completion.go +++ b/vendor/github.com/olivere/elastic/v7/suggester_completion.go @@ -8,7 +8,7 @@ import "errors" // CompletionSuggester is a fast suggester for e.g. type-ahead completion. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-completion.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-completion.html // for more details. type CompletionSuggester struct { Suggester @@ -21,7 +21,6 @@ type CompletionSuggester struct { size *int shardSize *int contextQueries []SuggesterContextQuery - payload interface{} fuzzyOptions *FuzzyCompletionSuggesterOptions regexOptions *RegexCompletionSuggesterOptions @@ -245,7 +244,7 @@ func NewFuzzyCompletionSuggesterOptions() *FuzzyCompletionSuggesterOptions { // EditDistance specifies the maximum number of edits, e.g. a number like "1" or "2" // or a string like "0..2" or ">5". // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/common-options.html#fuzziness +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/common-options.html#fuzziness // for details. func (o *FuzzyCompletionSuggesterOptions) EditDistance(editDistance interface{}) *FuzzyCompletionSuggesterOptions { o.editDistance = editDistance @@ -328,7 +327,7 @@ func NewRegexCompletionSuggesterOptions() *RegexCompletionSuggesterOptions { // Flags represents internal regex flags. // Possible flags are ALL (default), ANYSTRING, COMPLEMENT, EMPTY, INTERSECTION, INTERVAL, or NONE. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-completion.html#regex +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-completion.html#regex // for details. func (o *RegexCompletionSuggesterOptions) Flags(flags interface{}) *RegexCompletionSuggesterOptions { o.flags = flags @@ -337,7 +336,7 @@ func (o *RegexCompletionSuggesterOptions) Flags(flags interface{}) *RegexComplet // MaxDeterminizedStates represents the maximum automaton states allowed for regex expansion. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-completion.html#regex +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-completion.html#regex // for details. func (o *RegexCompletionSuggesterOptions) MaxDeterminizedStates(max int) *RegexCompletionSuggesterOptions { o.maxDeterminizedStates = &max diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_context.go b/vendor/github.com/olivere/elastic/v7/suggester_context.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_context.go rename to vendor/github.com/olivere/elastic/v7/suggester_context.go index 5b15088..fa6e445 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_context.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/suggester-context.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/suggester-context.html // for more details. type ContextSuggester struct { Suggester diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_context_category.go b/vendor/github.com/olivere/elastic/v7/suggester_context_category.go similarity index 74% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_context_category.go rename to vendor/github.com/olivere/elastic/v7/suggester_context_category.go index 134ecc7..ccca301 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_context_category.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/suggester-context.html#_category_mapping. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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.2/suggester-context.html#_category_query. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/suggester-context.html#_category_query. type SuggesterCategoryQuery struct { name string values map[string]*int @@ -117,3 +117,38 @@ func (q *SuggesterCategoryQuery) Source() (interface{}, error) { return source, nil } + +type SuggesterCategoryIndex struct { + name string + values []string +} + +// NewSuggesterCategoryIndex creates a new SuggesterCategoryIndex. +func NewSuggesterCategoryIndex(name string, values ...string) *SuggesterCategoryIndex { + q := &SuggesterCategoryIndex{ + name: name, + values: values, + } + return q +} + +func (q *SuggesterCategoryIndex) Values(values ...string) *SuggesterCategoryIndex { + q.values = append(q.values, values...) + return q +} + +// Source returns a map that will be used to serialize the context query as JSON. +func (q *SuggesterCategoryIndex) Source() (interface{}, error) { + source := make(map[string]interface{}) + + switch len(q.values) { + case 0: + source[q.name] = make([]string, 0) + case 1: + source[q.name] = q.values[0] + default: + source[q.name] = q.values + } + + return source, nil +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_context_geo.go b/vendor/github.com/olivere/elastic/v7/suggester_context_geo.go similarity index 56% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_context_geo.go rename to vendor/github.com/olivere/elastic/v7/suggester_context_geo.go index 88b8cdb..82ddd57 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_context_geo.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/suggester-context.html#_geo_location_mapping. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/suggester-context.html#_geo_location_mapping. type SuggesterGeoMapping struct { name string defaultLocations []*GeoPoint @@ -80,24 +80,36 @@ 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.2/suggester-context.html#_geo_location_query +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/suggester-context.html#_geo_location_query type SuggesterGeoQuery struct { - name string - location *GeoPoint - precision []string + name string + location *GeoPoint + precision string + neighbours []string + boost *int } // NewSuggesterGeoQuery creates a new SuggesterGeoQuery. func NewSuggesterGeoQuery(name string, location *GeoPoint) *SuggesterGeoQuery { return &SuggesterGeoQuery{ - name: name, - location: location, - precision: make([]string, 0), + name: name, + location: location, + neighbours: make([]string, 0), } } -func (q *SuggesterGeoQuery) Precision(precision ...string) *SuggesterGeoQuery { - q.precision = append(q.precision, precision...) +func (q *SuggesterGeoQuery) Precision(precision string) *SuggesterGeoQuery { + q.precision = precision + return q +} + +func (q *SuggesterGeoQuery) Neighbours(neighbours ...string) *SuggesterGeoQuery { + q.neighbours = append(q.neighbours, neighbours...) + return q +} + +func (q *SuggesterGeoQuery) Boost(boost int) *SuggesterGeoQuery { + q.boost = &boost return q } @@ -105,25 +117,61 @@ func (q *SuggesterGeoQuery) Precision(precision ...string) *SuggesterGeoQuery { func (q *SuggesterGeoQuery) Source() (interface{}, error) { source := make(map[string]interface{}) - if len(q.precision) == 0 { - if q.location != nil { - source[q.name] = q.location.Source() - } - } else { - x := make(map[string]interface{}) - source[q.name] = x + x := make(map[string]interface{}) + source[q.name] = x - if q.location != nil { - x["value"] = q.location.Source() - } + if q.location != nil { + x["context"] = q.location.Source() + } + if q.precision != "" { + x["precision"] = q.precision + } + if q.boost != nil { + x["boost"] = q.boost + } + switch len(q.neighbours) { + case 0: + case 1: + x["neighbours"] = q.neighbours[0] + default: + x["neighbours"] = q.neighbours + } + + return source, nil +} + +type SuggesterGeoIndex struct { + name string + locations []*GeoPoint +} - switch len(q.precision) { - case 0: - case 1: - x["precision"] = q.precision[0] - default: - x["precision"] = q.precision +// NewSuggesterGeoQuery creates a new SuggesterGeoQuery. +func NewSuggesterGeoIndex(name string) *SuggesterGeoIndex { + return &SuggesterGeoIndex{ + name: name, + } +} + +func (q *SuggesterGeoIndex) Locations(locations ...*GeoPoint) *SuggesterGeoIndex { + q.locations = append(q.locations, locations...) + return q +} + +// Source returns a map that will be used to serialize the context query as JSON. +func (q *SuggesterGeoIndex) Source() (interface{}, error) { + source := make(map[string]interface{}) + + switch len(q.locations) { + case 0: + source[q.name] = make([]string, 0) + case 1: + source[q.name] = q.locations[0].Source() + default: + var arr []interface{} + for _, p := range q.locations { + arr = append(arr, p.Source()) } + source[q.name] = arr } return source, nil diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_phrase.go b/vendor/github.com/olivere/elastic/v7/suggester_phrase.go similarity index 94% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_phrase.go rename to vendor/github.com/olivere/elastic/v7/suggester_phrase.go index 2fc9420..82ce443 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_phrase.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-suggesters-phrase.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-phrase.html. type PhraseSuggester struct { Suggester name string @@ -29,7 +29,7 @@ type PhraseSuggester struct { forceUnigrams *bool tokenLimit *int preTag, postTag *string - collateQuery *string + collateQuery *Script collatePreference *string collateParams map[string]interface{} collatePrune *bool @@ -154,8 +154,8 @@ func (q *PhraseSuggester) Highlight(preTag, postTag string) *PhraseSuggester { return q } -func (q *PhraseSuggester) CollateQuery(collateQuery string) *PhraseSuggester { - q.collateQuery = &collateQuery +func (q *PhraseSuggester) CollateQuery(collateQuery *Script) *PhraseSuggester { + q.collateQuery = collateQuery return q } @@ -282,7 +282,11 @@ func (q *PhraseSuggester) Source(includeName bool) (interface{}, error) { collate := make(map[string]interface{}) suggester["collate"] = collate if q.collateQuery != nil { - collate["query"] = *q.collateQuery + src, err := q.collateQuery.Source() + if err != nil { + return nil, err + } + collate["query"] = src } if q.collatePreference != nil { collate["preference"] = *q.collatePreference @@ -312,7 +316,7 @@ type SmoothingModel interface { } // StupidBackoffSmoothingModel implements a stupid backoff smoothing model. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-phrase.html#_smoothing_models +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models // for details about smoothing models. type StupidBackoffSmoothingModel struct { discount float64 @@ -337,7 +341,7 @@ func (sm *StupidBackoffSmoothingModel) Source() (interface{}, error) { // -- // LaplaceSmoothingModel implements a laplace smoothing model. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-phrase.html#_smoothing_models +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models // for details about smoothing models. type LaplaceSmoothingModel struct { alpha float64 @@ -363,7 +367,7 @@ func (sm *LaplaceSmoothingModel) Source() (interface{}, error) { // LinearInterpolationSmoothingModel implements a linear interpolation // smoothing model. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-phrase.html#_smoothing_models +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models // for details about smoothing models. type LinearInterpolationSmoothingModel struct { trigramLamda float64 @@ -399,7 +403,7 @@ type CandidateGenerator interface { } // DirectCandidateGenerator implements a direct candidate generator. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters-phrase.html#_smoothing_models +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models // for details about smoothing models. type DirectCandidateGenerator struct { field string diff --git a/vendor/gopkg.in/olivere/elastic.v6/suggester_term.go b/vendor/github.com/olivere/elastic/v7/suggester_term.go similarity index 97% rename from vendor/gopkg.in/olivere/elastic.v6/suggester_term.go rename to vendor/github.com/olivere/elastic/v7/suggester_term.go index fc51280..ecb6d9e 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/suggester_term.go +++ b/vendor/github.com/olivere/elastic/v7/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.2/search-suggesters-term.html. +// https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-term.html. type TermSuggester struct { Suggester name string @@ -217,7 +217,7 @@ func (q *TermSuggester) Source(includeName bool) (interface{}, error) { suggester["prefix_length"] = *q.prefixLength } if q.minWordLength != nil { - suggester["min_word_len"] = *q.minWordLength + suggester["min_word_length"] = *q.minWordLength } if q.minDocFreq != nil { suggester["min_doc_freq"] = *q.minDocFreq diff --git a/vendor/github.com/olivere/elastic/v7/tasks_cancel.go b/vendor/github.com/olivere/elastic/v7/tasks_cancel.go new file mode 100644 index 0000000..1294004 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/tasks_cancel.go @@ -0,0 +1,207 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// TasksCancelService can cancel long-running tasks. +// It is supported as of Elasticsearch 2.3.0. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/tasks.html#task-cancellation +// for details. +type TasksCancelService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + taskId string + actions []string + nodeId []string + parentTaskId string +} + +// NewTasksCancelService creates a new TasksCancelService. +func NewTasksCancelService(client *Client) *TasksCancelService { + return &TasksCancelService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *TasksCancelService) Pretty(pretty bool) *TasksCancelService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *TasksCancelService) Human(human bool) *TasksCancelService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *TasksCancelService) ErrorTrace(errorTrace bool) *TasksCancelService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *TasksCancelService) FilterPath(filterPath ...string) *TasksCancelService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *TasksCancelService) Header(name string, value string) *TasksCancelService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *TasksCancelService) Headers(headers http.Header) *TasksCancelService { + s.headers = headers + return s +} + +// TaskId specifies the task to cancel. Notice that the caller is responsible +// for using the correct format, i.e. node_id:task_number, as specified in +// the REST API. +func (s *TasksCancelService) TaskId(taskId string) *TasksCancelService { + s.taskId = taskId + return s +} + +// TaskIdFromNodeAndId specifies the task to cancel. Set id to -1 for all tasks. +func (s *TasksCancelService) TaskIdFromNodeAndId(nodeId string, id int64) *TasksCancelService { + if id != -1 { + s.taskId = fmt.Sprintf("%s:%d", nodeId, id) + } + return s +} + +// Actions is a list of actions that should be cancelled. Leave empty to cancel all. +func (s *TasksCancelService) Actions(actions ...string) *TasksCancelService { + s.actions = append(s.actions, actions...) + return s +} + +// NodeId is a list of node IDs or names to limit the returned information; +// use `_local` to return information from the node you're connecting to, +// leave empty to get information from all nodes. +func (s *TasksCancelService) NodeId(nodeId ...string) *TasksCancelService { + s.nodeId = append(s.nodeId, nodeId...) + return s +} + +// ParentTaskId specifies to cancel tasks with specified parent task id. +// Notice that the caller is responsible for using the correct format, +// i.e. node_id:task_number, as specified in the REST API. +func (s *TasksCancelService) ParentTaskId(parentTaskId string) *TasksCancelService { + s.parentTaskId = parentTaskId + return s +} + +// ParentTaskIdFromNodeAndId specifies to cancel tasks with specified parent task id. +func (s *TasksCancelService) ParentTaskIdFromNodeAndId(nodeId string, id int64) *TasksCancelService { + if id != -1 { + s.parentTaskId = fmt.Sprintf("%s:%d", nodeId, id) + } + return s +} + +// buildURL builds the URL for the operation. +func (s *TasksCancelService) buildURL() (string, url.Values, error) { + // Build URL + var err error + var path string + if s.taskId != "" { + path, err = uritemplates.Expand("/_tasks/{task_id}/_cancel", map[string]string{ + "task_id": s.taskId, + }) + } else { + path = "/_tasks/_cancel" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if len(s.actions) > 0 { + params.Set("actions", strings.Join(s.actions, ",")) + } + if len(s.nodeId) > 0 { + params.Set("nodes", strings.Join(s.nodeId, ",")) + } + if s.parentTaskId != "" { + params.Set("parent_task_id", s.parentTaskId) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *TasksCancelService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *TasksCancelService) Do(ctx context.Context) (*TasksListResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(TasksListResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} diff --git a/vendor/github.com/olivere/elastic/v7/tasks_get_task.go b/vendor/github.com/olivere/elastic/v7/tasks_get_task.go new file mode 100644 index 0000000..d9f8a8b --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/tasks_get_task.go @@ -0,0 +1,169 @@ +package elastic + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// TasksGetTaskService retrieves the state of a task in the cluster. It is part of the Task Management API +// documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/tasks.html#_current_tasks_information. +type TasksGetTaskService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + taskId string + waitForCompletion *bool +} + +// NewTasksGetTaskService creates a new TasksGetTaskService. +func NewTasksGetTaskService(client *Client) *TasksGetTaskService { + return &TasksGetTaskService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *TasksGetTaskService) Pretty(pretty bool) *TasksGetTaskService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *TasksGetTaskService) Human(human bool) *TasksGetTaskService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *TasksGetTaskService) ErrorTrace(errorTrace bool) *TasksGetTaskService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *TasksGetTaskService) FilterPath(filterPath ...string) *TasksGetTaskService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *TasksGetTaskService) Header(name string, value string) *TasksGetTaskService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *TasksGetTaskService) Headers(headers http.Header) *TasksGetTaskService { + s.headers = headers + return s +} + +// TaskId specifies the task to return. Notice that the caller is responsible +// for using the correct format, i.e. node_id:task_number, as specified in +// the REST API. +func (s *TasksGetTaskService) TaskId(taskId string) *TasksGetTaskService { + s.taskId = taskId + return s +} + +// TaskIdFromNodeAndId indicates to return the task on the given node with specified id. +func (s *TasksGetTaskService) TaskIdFromNodeAndId(nodeId string, id int64) *TasksGetTaskService { + s.taskId = fmt.Sprintf("%s:%d", nodeId, id) + return s +} + +// WaitForCompletion indicates whether to wait for the matching tasks +// to complete (default: false). +func (s *TasksGetTaskService) WaitForCompletion(waitForCompletion bool) *TasksGetTaskService { + s.waitForCompletion = &waitForCompletion + return s +} + +// buildURL builds the URL for the operation. +func (s *TasksGetTaskService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_tasks/{task_id}", map[string]string{ + "task_id": s.taskId, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.waitForCompletion; v != nil { + params.Set("wait_for_completion", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *TasksGetTaskService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *TasksGetTaskService) Do(ctx context.Context) (*TasksGetTaskResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(TasksGetTaskResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + ret.Header = res.Header + return ret, nil +} + +type TasksGetTaskResponse struct { + Header http.Header `json:"-"` + Completed bool `json:"completed"` + Task *TaskInfo `json:"task,omitempty"` + Error *ErrorDetails `json:"error,omitempty"` +} diff --git a/vendor/gopkg.in/olivere/elastic.v6/tasks_list.go b/vendor/github.com/olivere/elastic/v7/tasks_list.go similarity index 59% rename from vendor/gopkg.in/olivere/elastic.v6/tasks_list.go rename to vendor/github.com/olivere/elastic/v7/tasks_list.go index bbbe9af..dc1ad49 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/tasks_list.go +++ b/vendor/github.com/olivere/elastic/v7/tasks_list.go @@ -7,27 +7,32 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/tasks.html. +// documented at https://www.elastic.co/guide/en/elasticsearch/reference/7.0/tasks.html. // // It is supported as of Elasticsearch 2.3.0. type TasksListService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + taskId []string actions []string detailed *bool - human *bool nodeId []string - parentNode string - parentTaskId *string + parentTaskId string waitForCompletion *bool groupBy string } @@ -39,7 +44,49 @@ func NewTasksListService(client *Client) *TasksListService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *TasksListService) Pretty(pretty bool) *TasksListService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *TasksListService) Human(human bool) *TasksListService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *TasksListService) ErrorTrace(errorTrace bool) *TasksListService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *TasksListService) FilterPath(filterPath ...string) *TasksListService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *TasksListService) Header(name string, value string) *TasksListService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *TasksListService) Headers(headers http.Header) *TasksListService { + s.headers = headers + return s +} + // TaskId indicates to returns the task(s) with specified id(s). +// Notice that the caller is responsible for using the correct format, +// i.e. node_id:task_number, as specified in the REST API. func (s *TasksListService) TaskId(taskId ...string) *TasksListService { s.taskId = append(s.taskId, taskId...) return s @@ -57,12 +104,6 @@ func (s *TasksListService) Detailed(detailed bool) *TasksListService { return s } -// Human indicates whether to return time and byte values in human-readable format. -func (s *TasksListService) Human(human bool) *TasksListService { - s.human = &human - return s -} - // NodeId is a list of node IDs or names to limit the returned information; // use `_local` to return information from the node you're connecting to, // leave empty to get information from all nodes. @@ -71,15 +112,11 @@ func (s *TasksListService) NodeId(nodeId ...string) *TasksListService { return s } -// ParentNode returns tasks with specified parent node. -func (s *TasksListService) ParentNode(parentNode string) *TasksListService { - s.parentNode = parentNode - return s -} - -// ParentTaskId returns tasks with specified parent task id (node_id:task_number). Set to -1 to return all. +// ParentTaskId returns tasks with specified parent task id. +// Notice that the caller is responsible for using the correct format, +// i.e. node_id:task_number, as specified in the REST API. func (s *TasksListService) ParentTaskId(parentTaskId string) *TasksListService { - s.parentTaskId = &parentTaskId + s.parentTaskId = parentTaskId return s } @@ -91,18 +128,12 @@ func (s *TasksListService) WaitForCompletion(waitForCompletion bool) *TasksListS } // GroupBy groups tasks by nodes or parent/child relationships. -// As of now, it can either be "nodes" (default) or "parents". +// As of now, it can either be "nodes" (default) or "parents" or "none". func (s *TasksListService) GroupBy(groupBy string) *TasksListService { s.groupBy = groupBy return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *TasksListService) Pretty(pretty bool) *TasksListService { - s.pretty = pretty - return s -} - // buildURL builds the URL for the operation. func (s *TasksListService) buildURL() (string, url.Values, error) { // Build URL @@ -121,29 +152,32 @@ func (s *TasksListService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if len(s.actions) > 0 { params.Set("actions", strings.Join(s.actions, ",")) } - if s.detailed != nil { - params.Set("detailed", fmt.Sprintf("%v", *s.detailed)) - } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) + if v := s.detailed; v != nil { + params.Set("detailed", fmt.Sprint(*v)) } if len(s.nodeId) > 0 { - params.Set("node_id", strings.Join(s.nodeId, ",")) - } - if s.parentNode != "" { - params.Set("parent_node", s.parentNode) + params.Set("nodes", strings.Join(s.nodeId, ",")) } - if s.parentTaskId != nil { - params.Set("parent_task_id", *s.parentTaskId) + if s.parentTaskId != "" { + params.Set("parent_task_id", s.parentTaskId) } - if s.waitForCompletion != nil { - params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion)) + if v := s.waitForCompletion; v != nil { + params.Set("wait_for_completion", fmt.Sprint(*v)) } if s.groupBy != "" { params.Set("group_by", s.groupBy) @@ -171,9 +205,10 @@ 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, + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, }) if err != nil { return nil, err @@ -184,11 +219,13 @@ func (s *TasksListService) Do(ctx context.Context) (*TasksListResponse, error) { if err := s.client.decoder.Decode(res.Body, ret); err != nil { return nil, err } + ret.Header = res.Header return ret, nil } // TasksListResponse is the response of TasksListService.Do. type TasksListResponse struct { + Header http.Header `json:"-"` TaskFailures []*TaskOperationFailure `json:"task_failures"` NodeFailures []*FailedNodeException `json:"node_failures"` // Nodes returns the tasks per node. The key is the node id. @@ -220,22 +257,24 @@ type DiscoveryNode struct { // TaskInfo represents information about a currently running task. type TaskInfo struct { - Node string `json:"node"` - Id int64 `json:"id"` // the task id (yes, this is a long in the Java source) - Type string `json:"type"` - Action string `json:"action"` - Status interface{} `json:"status"` // has separate implementations of Task.Status in Java for reindexing, replication, and "RawTaskStatus" - Description interface{} `json:"description"` // same as Status - StartTime string `json:"start_time"` - StartTimeInMillis int64 `json:"start_time_in_millis"` - RunningTime string `json:"running_time"` - RunningTimeInNanos int64 `json:"running_time_in_nanos"` - Cancellable bool `json:"cancellable"` - ParentTaskId string `json:"parent_task_id"` // like "YxJnVYjwSBm_AUbzddTajQ:12356" + Node string `json:"node"` + Id int64 `json:"id"` // the task id (yes, this is a long in the Java source) + Type string `json:"type"` + Action string `json:"action"` + Status interface{} `json:"status"` // has separate implementations of Task.Status in Java for reindexing, replication, and "RawTaskStatus" + Description interface{} `json:"description"` // same as Status + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTime string `json:"running_time"` + RunningTimeInNanos int64 `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + ParentTaskId string `json:"parent_task_id"` // like "YxJnVYjwSBm_AUbzddTajQ:12356" + Headers map[string]string `json:"headers"` } // StartTaskResult is used in cases where a task gets started asynchronously and // the operation simply returnes a TaskID to watch for via the Task Management API. type StartTaskResult struct { - TaskId string `json:"task"` + Header http.Header `json:"-"` + TaskId string `json:"task"` } diff --git a/vendor/gopkg.in/olivere/elastic.v6/termvectors.go b/vendor/github.com/olivere/elastic/v7/termvectors.go similarity index 79% rename from vendor/gopkg.in/olivere/elastic.v6/termvectors.go rename to vendor/github.com/olivere/elastic/v7/termvectors.go index a3b4875..a196810 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/termvectors.go +++ b/vendor/github.com/olivere/elastic/v7/termvectors.go @@ -7,21 +7,28 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/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.2/docs-termvectors.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-termvectors.html // for documentation. type TermvectorsService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + id string index string typ string @@ -52,6 +59,46 @@ func NewTermvectorsService(client *Client) *TermvectorsService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *TermvectorsService) Pretty(pretty bool) *TermvectorsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *TermvectorsService) Human(human bool) *TermvectorsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *TermvectorsService) ErrorTrace(errorTrace bool) *TermvectorsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *TermvectorsService) FilterPath(filterPath ...string) *TermvectorsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *TermvectorsService) Header(name string, value string) *TermvectorsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *TermvectorsService) Headers(headers http.Header) *TermvectorsService { + s.headers = headers + return s +} + // Index in which the document resides. func (s *TermvectorsService) Index(index string) *TermvectorsService { s.index = index @@ -59,6 +106,8 @@ func (s *TermvectorsService) Index(index string) *TermvectorsService { } // Type of the document. +// +// Deprecated: Types are in the process of being removed. func (s *TermvectorsService) Type(typ string) *TermvectorsService { s.typ = typ return s @@ -175,12 +224,6 @@ func (s *TermvectorsService) VersionType(versionType string) *TermvectorsService return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *TermvectorsService) Pretty(pretty bool) *TermvectorsService { - s.pretty = pretty - return s -} - // BodyJson defines the body parameters. See documentation. func (s *TermvectorsService) BodyJson(body interface{}) *TermvectorsService { s.bodyJson = body @@ -197,60 +240,75 @@ func (s *TermvectorsService) BodyString(body string) *TermvectorsService { func (s *TermvectorsService) buildURL() (string, url.Values, error) { var pathParam = map[string]string{ "index": s.index, - "type": s.typ, } - var path string + path := "/{index}" var err error - // Build URL + if s.typ != "" { + pathParam["type"] = s.typ + path += "/{type}" + } else { + path += "/_termvectors" + } if s.id != "" { pathParam["id"] = s.id - path, err = uritemplates.Expand("/{index}/{type}/{id}/_termvectors", pathParam) - } else { - path, err = uritemplates.Expand("/{index}/{type}/_termvectors", pathParam) + path += "/{id}" + } + if s.typ != "" { + path += "/_termvectors" } + path, err = uritemplates.Expand(path, pathParam) if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) } - if s.dfs != nil { - params.Set("dfs", fmt.Sprintf("%v", *s.dfs)) + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) } - if s.fieldStatistics != nil { - params.Set("field_statistics", fmt.Sprintf("%v", *s.fieldStatistics)) + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.dfs; v != nil { + params.Set("dfs", fmt.Sprint(*v)) + } + if v := s.fieldStatistics; v != nil { + params.Set("field_statistics", fmt.Sprint(*v)) } if len(s.fields) > 0 { params.Set("fields", strings.Join(s.fields, ",")) } - if s.offsets != nil { - params.Set("offsets", fmt.Sprintf("%v", *s.offsets)) + if v := s.offsets; v != nil { + params.Set("offsets", fmt.Sprint(*v)) } if s.parent != "" { params.Set("parent", s.parent) } - if s.payloads != nil { - params.Set("payloads", fmt.Sprintf("%v", *s.payloads)) + if v := s.payloads; v != nil { + params.Set("payloads", fmt.Sprint(*v)) } - if s.positions != nil { - params.Set("positions", fmt.Sprintf("%v", *s.positions)) + if v := s.positions; v != nil { + params.Set("positions", fmt.Sprint(*v)) } if s.preference != "" { params.Set("preference", s.preference) } - if s.realtime != nil { - params.Set("realtime", fmt.Sprintf("%v", *s.realtime)) + if v := s.realtime; v != nil { + params.Set("realtime", fmt.Sprint(*v)) } if s.routing != "" { params.Set("routing", s.routing) } - if s.termStatistics != nil { - params.Set("term_statistics", fmt.Sprintf("%v", *s.termStatistics)) + if v := s.termStatistics; v != nil { + params.Set("term_statistics", fmt.Sprint(*v)) } if s.version != nil { params.Set("version", fmt.Sprintf("%v", s.version)) @@ -267,9 +325,6 @@ func (s *TermvectorsService) Validate() error { if s.index == "" { invalid = append(invalid, "Index") } - if s.typ == "" { - invalid = append(invalid, "Type") - } if len(invalid) > 0 { return fmt.Errorf("missing required fields: %v", invalid) } @@ -317,10 +372,11 @@ 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, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err @@ -338,7 +394,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.2/docs-termvectors.html#_terms_filtering +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-termvectors.html#_terms_filtering // for more information. type TermvectorsFilterSettings struct { maxNumTerms *int64 diff --git a/vendor/github.com/olivere/elastic/v7/update.go b/vendor/github.com/olivere/elastic/v7/update.go new file mode 100644 index 0000000..468032e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/update.go @@ -0,0 +1,412 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// UpdateService updates a document in Elasticsearch. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update.html +// for details. +type UpdateService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + index string + typ string + id string + routing string + parent string + script *Script + fields []string + fsc *FetchSourceContext + version *int64 + versionType string + retryOnConflict *int + refresh string + waitForActiveShards string + upsert interface{} + scriptedUpsert *bool + docAsUpsert *bool + detectNoop *bool + doc interface{} + timeout string + ifSeqNo *int64 + ifPrimaryTerm *int64 +} + +// NewUpdateService creates the service to update documents in Elasticsearch. +func NewUpdateService(client *Client) *UpdateService { + return &UpdateService{ + client: client, + typ: "_doc", + fields: make([]string, 0), + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *UpdateService) Pretty(pretty bool) *UpdateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *UpdateService) Human(human bool) *UpdateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *UpdateService) ErrorTrace(errorTrace bool) *UpdateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *UpdateService) FilterPath(filterPath ...string) *UpdateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *UpdateService) Header(name string, value string) *UpdateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *UpdateService) Headers(headers http.Header) *UpdateService { + s.headers = headers + return s +} + +// Index is the name of the Elasticsearch index (required). +func (s *UpdateService) Index(name string) *UpdateService { + s.index = name + return s +} + +// Type is the type of the document. +// +// Deprecated: Types are in the process of being removed. +func (s *UpdateService) Type(typ string) *UpdateService { + s.typ = typ + return s +} + +// Id is the identifier of the document to update (required). +func (s *UpdateService) Id(id string) *UpdateService { + s.id = id + return s +} + +// Routing specifies a specific routing value. +func (s *UpdateService) Routing(routing string) *UpdateService { + s.routing = routing + return s +} + +// Parent sets the id of the parent document. +func (s *UpdateService) Parent(parent string) *UpdateService { + s.parent = parent + return s +} + +// Script is the script definition. +func (s *UpdateService) Script(script *Script) *UpdateService { + s.script = script + return s +} + +// RetryOnConflict specifies how many times the operation should be retried +// when a conflict occurs (default: 0). +func (s *UpdateService) RetryOnConflict(retryOnConflict int) *UpdateService { + s.retryOnConflict = &retryOnConflict + return s +} + +// Fields is a list of fields to return in the response. +func (s *UpdateService) Fields(fields ...string) *UpdateService { + s.fields = make([]string, 0, len(fields)) + s.fields = append(s.fields, fields...) + return s +} + +// Version defines the explicit version number for concurrency control. +func (s *UpdateService) Version(version int64) *UpdateService { + s.version = &version + return s +} + +// VersionType is e.g. "internal". +func (s *UpdateService) VersionType(versionType string) *UpdateService { + s.versionType = versionType + return s +} + +// Refresh the index after performing the update. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html +// for details. +func (s *UpdateService) Refresh(refresh string) *UpdateService { + s.refresh = refresh + return s +} + +// WaitForActiveShards sets the number of shard copies that must be active before +// proceeding with the update operation. Defaults to 1, meaning the primary shard only. +// Set to `all` for all shard copies, otherwise set to any non-negative value less than +// or equal to the total number of copies for the shard (number of replicas + 1). +func (s *UpdateService) WaitForActiveShards(waitForActiveShards string) *UpdateService { + s.waitForActiveShards = waitForActiveShards + return s +} + +// Doc allows for updating a partial document. +func (s *UpdateService) Doc(doc interface{}) *UpdateService { + s.doc = doc + return s +} + +// Upsert can be used to index the document when it doesn't exist yet. +// Use this e.g. to initialize a document with a default value. +func (s *UpdateService) Upsert(doc interface{}) *UpdateService { + s.upsert = doc + return s +} + +// DocAsUpsert can be used to insert the document if it doesn't already exist. +func (s *UpdateService) DocAsUpsert(docAsUpsert bool) *UpdateService { + s.docAsUpsert = &docAsUpsert + return s +} + +// DetectNoop will instruct Elasticsearch to check if changes will occur +// when updating via Doc. It there aren't any changes, the request will +// turn into a no-op. +func (s *UpdateService) DetectNoop(detectNoop bool) *UpdateService { + s.detectNoop = &detectNoop + return s +} + +// ScriptedUpsert should be set to true if the referenced script +// (defined in Script or ScriptId) should be called to perform an insert. +// The default is false. +func (s *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService { + s.scriptedUpsert = &scriptedUpsert + return s +} + +// Timeout is an explicit timeout for the operation, e.g. "1000", "1s" or "500ms". +func (s *UpdateService) Timeout(timeout string) *UpdateService { + s.timeout = timeout + return s +} + +// IfSeqNo indicates to only perform the update operation if the last +// operation that has changed the document has the specified sequence number. +func (s *UpdateService) IfSeqNo(seqNo int64) *UpdateService { + s.ifSeqNo = &seqNo + return s +} + +// IfPrimaryTerm indicates to only perform the update operation if the +// last operation that has changed the document has the specified primary term. +func (s *UpdateService) IfPrimaryTerm(primaryTerm int64) *UpdateService { + s.ifPrimaryTerm = &primaryTerm + return s +} + +// FetchSource asks Elasticsearch to return the updated _source in the response. +func (s *UpdateService) FetchSource(fetchSource bool) *UpdateService { + if s.fsc == nil { + s.fsc = NewFetchSourceContext(fetchSource) + } else { + s.fsc.SetFetchSource(fetchSource) + } + return s +} + +// FetchSourceContext indicates that _source should be returned in the response, +// allowing wildcard patterns to be defined via FetchSourceContext. +func (s *UpdateService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *UpdateService { + s.fsc = fetchSourceContext + return s +} + +// url returns the URL part of the document request. +func (s *UpdateService) url() (string, url.Values, error) { + // Build url + var path string + var err error + if s.typ == "" || s.typ == "_doc" { + path, err = uritemplates.Expand("/{index}/_update/{id}", map[string]string{ + "index": s.index, + "id": s.id, + }) + } else { + path, err = uritemplates.Expand("/{index}/{type}/{id}/_update", map[string]string{ + "index": s.index, + "type": s.typ, + "id": s.id, + }) + } + if err != nil { + return "", url.Values{}, err + } + + // Parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.routing != "" { + params.Set("routing", s.routing) + } + if s.parent != "" { + params.Set("parent", s.parent) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.refresh != "" { + params.Set("refresh", s.refresh) + } + if s.waitForActiveShards != "" { + params.Set("wait_for_active_shards", s.waitForActiveShards) + } + if len(s.fields) > 0 { + params.Set("fields", strings.Join(s.fields, ",")) + } + if s.version != nil { + params.Set("version", fmt.Sprintf("%d", *s.version)) + } + if s.versionType != "" { + params.Set("version_type", s.versionType) + } + if s.retryOnConflict != nil { + params.Set("retry_on_conflict", fmt.Sprintf("%v", *s.retryOnConflict)) + } + if v := s.ifSeqNo; v != nil { + params.Set("if_seq_no", fmt.Sprintf("%d", *v)) + } + if v := s.ifPrimaryTerm; v != nil { + params.Set("if_primary_term", fmt.Sprintf("%d", *v)) + } + return path, params, nil +} + +// body returns the body part of the document request. +func (s *UpdateService) body() (interface{}, error) { + source := make(map[string]interface{}) + + if s.script != nil { + src, err := s.script.Source() + if err != nil { + return nil, err + } + source["script"] = src + } + + if v := s.scriptedUpsert; v != nil { + source["scripted_upsert"] = *v + } + + if s.upsert != nil { + source["upsert"] = s.upsert + } + + if s.doc != nil { + source["doc"] = s.doc + } + if v := s.docAsUpsert; v != nil { + source["doc_as_upsert"] = *v + } + if v := s.detectNoop; v != nil { + source["detect_noop"] = *v + } + if s.fsc != nil { + src, err := s.fsc.Source() + if err != nil { + return nil, err + } + source["_source"] = src + } + + return source, nil +} + +// Do executes the update operation. +func (s *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) { + path, params, err := s.url() + if err != nil { + return nil, err + } + + // Get body of the request + body, err := s.body() + if err != nil { + return nil, err + } + + // Get response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return result + ret := new(UpdateResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// 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"` + 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.v6/update_by_query.go b/vendor/github.com/olivere/elastic/v7/update_by_query.go similarity index 85% rename from vendor/gopkg.in/olivere/elastic.v6/update_by_query.go rename to vendor/github.com/olivere/elastic/v7/update_by_query.go index cd35f02..8fdffd3 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/update_by_query.go +++ b/vendor/github.com/olivere/elastic/v7/update_by_query.go @@ -7,16 +7,23 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // UpdateByQueryService is documented at https://www.elastic.co/guide/en/elasticsearch/plugins/master/plugins-reindex.html. type UpdateByQueryService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string script *Script @@ -75,6 +82,46 @@ func NewUpdateByQueryService(client *Client) *UpdateByQueryService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *UpdateByQueryService) Pretty(pretty bool) *UpdateByQueryService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *UpdateByQueryService) Human(human bool) *UpdateByQueryService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *UpdateByQueryService) ErrorTrace(errorTrace bool) *UpdateByQueryService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *UpdateByQueryService) FilterPath(filterPath ...string) *UpdateByQueryService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *UpdateByQueryService) Header(name string, value string) *UpdateByQueryService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *UpdateByQueryService) Headers(headers http.Header) *UpdateByQueryService { + s.headers = headers + return s +} + // Index is a list of index names to search; use `_all` or empty string to // perform the operation on all indices. func (s *UpdateByQueryService) Index(index ...string) *UpdateByQueryService { @@ -89,12 +136,6 @@ func (s *UpdateByQueryService) Type(typ ...string) *UpdateByQueryService { return s } -// Pretty indicates that the JSON response be indented and human readable. -func (s *UpdateByQueryService) Pretty(pretty bool) *UpdateByQueryService { - s.pretty = pretty - return s -} - // Script sets an update script. func (s *UpdateByQueryService) Script(script *Script) *UpdateByQueryService { s.script = script @@ -261,7 +302,7 @@ func (s *UpdateByQueryService) Query(query Query) *UpdateByQueryService { // Refresh indicates whether the effected indexes should be refreshed. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html // for details. func (s *UpdateByQueryService) Refresh(refresh string) *UpdateByQueryService { s.refresh = refresh @@ -322,9 +363,9 @@ func (s *UpdateByQueryService) Size(size int) *UpdateByQueryService { } // Slices represents the number of slices (default: 1). -// It used to be a number, but can be set to "auto" as of 6.3. +// It used to be a number, but can be set to "auto" as of 6.7. // -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/docs-update-by-query.html#docs-update-by-query-slice +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update-by-query.html#docs-update-by-query-slice // for details. func (s *UpdateByQueryService) Slices(slices interface{}) *UpdateByQueryService { s.slices = slices @@ -460,17 +501,26 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if len(s.xSource) > 0 { params.Set("_source", strings.Join(s.xSource, ",")) } if len(s.xSourceExclude) > 0 { - params.Set("_source_exclude", strings.Join(s.xSourceExclude, ",")) + params.Set("_source_excludes", strings.Join(s.xSourceExclude, ",")) } if len(s.xSourceInclude) > 0 { - params.Set("_source_include", strings.Join(s.xSourceInclude, ",")) + params.Set("_source_includes", strings.Join(s.xSourceInclude, ",")) } if s.allowNoIndices != nil { params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) @@ -478,8 +528,8 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { if s.analyzer != "" { params.Set("analyzer", s.analyzer) } - if s.analyzeWildcard != nil { - params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard)) + if v := s.analyzeWildcard; v != nil { + params.Set("analyze_wildcard", fmt.Sprint(*v)) } if s.conflicts != "" { params.Set("conflicts", s.conflicts) @@ -493,8 +543,8 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) } - if s.explain != nil { - params.Set("explain", fmt.Sprintf("%v", *s.explain)) + if v := s.explain; v != nil { + params.Set("explain", fmt.Sprint(*v)) } if len(s.storedFields) > 0 { params.Set("stored_fields", strings.Join(s.storedFields, ",")) @@ -508,14 +558,14 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { if s.from != nil { params.Set("from", fmt.Sprintf("%d", *s.from)) } - if s.ignoreUnavailable != nil { - params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) } - if s.lenient != nil { - params.Set("lenient", fmt.Sprintf("%v", *s.lenient)) + if v := s.lenient; v != nil { + params.Set("lenient", fmt.Sprint(*v)) } - if s.lowercaseExpandedTerms != nil { - params.Set("lowercase_expanded_terms", fmt.Sprintf("%v", *s.lowercaseExpandedTerms)) + if v := s.lowercaseExpandedTerms; v != nil { + params.Set("lowercase_expanded_terms", fmt.Sprint(*v)) } if s.pipeline != "" { params.Set("pipeline", s.pipeline) @@ -529,8 +579,8 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { if s.refresh != "" { params.Set("refresh", s.refresh) } - if s.requestCache != nil { - params.Set("request_cache", fmt.Sprintf("%v", *s.requestCache)) + if v := s.requestCache; v != nil { + params.Set("request_cache", fmt.Sprint(*v)) } if len(s.routing) > 0 { params.Set("routing", strings.Join(s.routing, ",")) @@ -577,20 +627,20 @@ func (s *UpdateByQueryService) buildURL() (string, url.Values, error) { if s.timeout != "" { params.Set("timeout", s.timeout) } - if s.trackScores != nil { - params.Set("track_scores", fmt.Sprintf("%v", *s.trackScores)) + if v := s.trackScores; v != nil { + params.Set("track_scores", fmt.Sprint(*v)) } - if s.version != nil { - params.Set("version", fmt.Sprintf("%v", *s.version)) + if v := s.version; v != nil { + params.Set("version", fmt.Sprint(*v)) } - if s.versionType != nil { - params.Set("version_type", fmt.Sprintf("%v", *s.versionType)) + if v := s.versionType; v != nil { + params.Set("version_type", fmt.Sprint(*v)) } if s.waitForActiveShards != "" { params.Set("wait_for_active_shards", s.waitForActiveShards) } - if s.waitForCompletion != nil { - params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion)) + if v := s.waitForCompletion; v != nil { + params.Set("wait_for_completion", fmt.Sprint(*v)) } if s.requestsPerSecond != nil { params.Set("requests_per_second", fmt.Sprintf("%v", *s.requestsPerSecond)) @@ -654,10 +704,12 @@ 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, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + IgnoreErrors: []int{http.StatusConflict}, }) if err != nil { return nil, err @@ -701,10 +753,12 @@ func (s *UpdateByQueryService) DoAsync(ctx context.Context) (*StartTaskResult, e // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + IgnoreErrors: []int{http.StatusConflict}, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/uritemplates/LICENSE b/vendor/github.com/olivere/elastic/v7/uritemplates/LICENSE similarity index 100% rename from vendor/github.com/olivere/elastic/uritemplates/LICENSE rename to vendor/github.com/olivere/elastic/v7/uritemplates/LICENSE diff --git a/vendor/github.com/olivere/elastic/uritemplates/uritemplates.go b/vendor/github.com/olivere/elastic/v7/uritemplates/uritemplates.go similarity index 99% rename from vendor/github.com/olivere/elastic/uritemplates/uritemplates.go rename to vendor/github.com/olivere/elastic/v7/uritemplates/uritemplates.go index 8a84813..fdb9cb4 100644 --- a/vendor/github.com/olivere/elastic/uritemplates/uritemplates.go +++ b/vendor/github.com/olivere/elastic/v7/uritemplates/uritemplates.go @@ -12,7 +12,7 @@ // values := make(map[string]interface{}) // values["user"] = "jtacoma" // values["repo"] = "uritemplates" -// expanded, _ := template.ExpandString(values) +// expanded, _ := template.Expand(values) // fmt.Printf(expanded) // package uritemplates diff --git a/vendor/github.com/olivere/elastic/uritemplates/utils.go b/vendor/github.com/olivere/elastic/v7/uritemplates/utils.go similarity index 100% rename from vendor/github.com/olivere/elastic/uritemplates/utils.go rename to vendor/github.com/olivere/elastic/v7/uritemplates/utils.go diff --git a/vendor/gopkg.in/olivere/elastic.v6/validate.go b/vendor/github.com/olivere/elastic/v7/validate.go similarity index 73% rename from vendor/gopkg.in/olivere/elastic.v6/validate.go rename to vendor/github.com/olivere/elastic/v7/validate.go index b232963..7ed9158 100644 --- a/vendor/gopkg.in/olivere/elastic.v6/validate.go +++ b/vendor/github.com/olivere/elastic/v7/validate.go @@ -7,18 +7,25 @@ package elastic import ( "context" "fmt" + "net/http" "net/url" "strings" - "github.com/olivere/elastic/uritemplates" + "github.com/olivere/elastic/v7/uritemplates" ) // ValidateService allows a user to validate a potentially // expensive query without executing it. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-validate.html. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-validate.html. type ValidateService struct { - client *Client - pretty bool + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + index []string typ []string q string @@ -44,13 +51,56 @@ func NewValidateService(client *Client) *ValidateService { } } +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *ValidateService) Pretty(pretty bool) *ValidateService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *ValidateService) Human(human bool) *ValidateService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *ValidateService) ErrorTrace(errorTrace bool) *ValidateService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *ValidateService) FilterPath(filterPath ...string) *ValidateService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *ValidateService) Header(name string, value string) *ValidateService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *ValidateService) Headers(headers http.Header) *ValidateService { + s.headers = headers + return s +} + // 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. +// Type adds search restrictions for a list of types. +// +// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to +// filter on a field on the document. func (s *ValidateService) Type(typ ...string) *ValidateService { s.typ = append(s.typ, typ...) return s @@ -112,12 +162,6 @@ func (s *ValidateService) DefaultOperator(defaultOperator string) *ValidateServi 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() @@ -190,8 +234,17 @@ func (s *ValidateService) buildURL() (string, url.Values, error) { // Add query string parameters params := url.Values{} - if s.pretty { - params.Set("pretty", "true") + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) } if s.explain != nil { params.Set("explain", fmt.Sprintf("%v", *s.explain)) @@ -205,14 +258,14 @@ func (s *ValidateService) buildURL() (string, url.Values, error) { if s.defaultOperator != "" { params.Set("default_operator", s.defaultOperator) } - if s.lenient != nil { - params.Set("lenient", fmt.Sprintf("%v", *s.lenient)) + if v := s.lenient; v != nil { + params.Set("lenient", fmt.Sprint(*v)) } if s.q != "" { params.Set("q", s.q) } - if s.analyzeWildcard != nil { - params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard)) + if v := s.analyzeWildcard; v != nil { + params.Set("analyze_wildcard", fmt.Sprint(*v)) } if s.analyzer != "" { params.Set("analyzer", s.analyzer) @@ -220,14 +273,14 @@ func (s *ValidateService) buildURL() (string, url.Values, error) { if s.df != "" { params.Set("df", s.df) } - if s.allowNoIndices != nil { - params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices)) + if v := s.allowNoIndices; v != nil { + params.Set("allow_no_indices", fmt.Sprint(*v)) } if s.expandWildcards != "" { params.Set("expand_wildcards", s.expandWildcards) } - if s.ignoreUnavailable != nil { - params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) + if v := s.ignoreUnavailable; v != nil { + params.Set("ignore_unavailable", fmt.Sprint(*v)) } return path, params, nil } @@ -260,10 +313,11 @@ func (s *ValidateService) Do(ctx context.Context) (*ValidateResponse, error) { // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, - Body: body, + Method: "GET", + Path: path, + Params: params, + Body: body, + Headers: s.headers, }) if err != nil { return nil, err diff --git a/vendor/github.com/olivere/elastic/v7/xpack_ilm_delete_lifecycle.go b/vendor/github.com/olivere/elastic/v7/xpack_ilm_delete_lifecycle.go new file mode 100644 index 0000000..bd60fde --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_ilm_delete_lifecycle.go @@ -0,0 +1,194 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// See the documentation at +// https://www.elastic.co/guide/en/elasticsearch/reference/6.7/ilm-get-lifecycle.html. +type XPackIlmDeleteLifecycleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + policy string + timeout string + masterTimeout string + flatSettings *bool + local *bool +} + +// NewXPackIlmDeleteLifecycleService creates a new XPackIlmDeleteLifecycleService. +func NewXPackIlmDeleteLifecycleService(client *Client) *XPackIlmDeleteLifecycleService { + return &XPackIlmDeleteLifecycleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackIlmDeleteLifecycleService) Pretty(pretty bool) *XPackIlmDeleteLifecycleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackIlmDeleteLifecycleService) Human(human bool) *XPackIlmDeleteLifecycleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackIlmDeleteLifecycleService) ErrorTrace(errorTrace bool) *XPackIlmDeleteLifecycleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackIlmDeleteLifecycleService) FilterPath(filterPath ...string) *XPackIlmDeleteLifecycleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackIlmDeleteLifecycleService) Header(name string, value string) *XPackIlmDeleteLifecycleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackIlmDeleteLifecycleService) Headers(headers http.Header) *XPackIlmDeleteLifecycleService { + s.headers = headers + return s +} + +// Policy is the name of the index lifecycle policy. +func (s *XPackIlmDeleteLifecycleService) Policy(policy string) *XPackIlmDeleteLifecycleService { + s.policy = policy + return s +} + +// Timeout is an explicit operation timeout. +func (s *XPackIlmDeleteLifecycleService) Timeout(timeout string) *XPackIlmDeleteLifecycleService { + s.timeout = timeout + return s +} + +// MasterTimeout specifies the timeout for connection to master. +func (s *XPackIlmDeleteLifecycleService) MasterTimeout(masterTimeout string) *XPackIlmDeleteLifecycleService { + s.masterTimeout = masterTimeout + return s +} + +// FlatSettings is returns settings in flat format (default: false). +func (s *XPackIlmDeleteLifecycleService) FlatSettings(flatSettings bool) *XPackIlmDeleteLifecycleService { + s.flatSettings = &flatSettings + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackIlmDeleteLifecycleService) buildURL() (string, url.Values, error) { + // Build URL + var err error + var path string + path, err = uritemplates.Expand("/_ilm/policy/{policy}", map[string]string{ + "policy": s.policy, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.flatSettings; v != nil { + params.Set("flat_settings", fmt.Sprint(*v)) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.local; v != nil { + params.Set("local", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackIlmDeleteLifecycleService) Validate() error { + var invalid []string + if s.policy == "" { + invalid = append(invalid, "Policy") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackIlmDeleteLifecycleService) Do(ctx context.Context) (*XPackIlmDeleteLifecycleResponse, error) { + // Check pre-conditions + if err := s.Validate(); err != nil { + return nil, err + } + + // Delete URL for request + path, params, err := s.buildURL() + if err != nil { + return nil, err + } + + // Delete HTTP response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackIlmDeleteLifecycleResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackIlmDeleteLifecycleResponse is the response of XPackIlmDeleteLifecycleService.Do. +type XPackIlmDeleteLifecycleResponse struct { + Acknowledged bool `json:"acknowledged"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_ilm_get_lifecycle.go b/vendor/github.com/olivere/elastic/v7/xpack_ilm_get_lifecycle.go new file mode 100644 index 0000000..3a52c36 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_ilm_get_lifecycle.go @@ -0,0 +1,193 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// See the documentation at +// https://www.elastic.co/guide/en/elasticsearch/reference/6.7/ilm-get-lifecycle.html. +type XPackIlmGetLifecycleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + policy []string + timeout string + masterTimeout string + flatSettings *bool + local *bool +} + +// NewXPackIlmGetLifecycleService creates a new XPackIlmGetLifecycleService. +func NewXPackIlmGetLifecycleService(client *Client) *XPackIlmGetLifecycleService { + return &XPackIlmGetLifecycleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackIlmGetLifecycleService) Pretty(pretty bool) *XPackIlmGetLifecycleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackIlmGetLifecycleService) Human(human bool) *XPackIlmGetLifecycleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackIlmGetLifecycleService) ErrorTrace(errorTrace bool) *XPackIlmGetLifecycleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackIlmGetLifecycleService) FilterPath(filterPath ...string) *XPackIlmGetLifecycleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackIlmGetLifecycleService) Header(name string, value string) *XPackIlmGetLifecycleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackIlmGetLifecycleService) Headers(headers http.Header) *XPackIlmGetLifecycleService { + s.headers = headers + return s +} + +// Policy is the name of the index lifecycle policy. +func (s *XPackIlmGetLifecycleService) Policy(policies ...string) *XPackIlmGetLifecycleService { + s.policy = append(s.policy, policies...) + return s +} + +// Timeout is an explicit operation timeout. +func (s *XPackIlmGetLifecycleService) Timeout(timeout string) *XPackIlmGetLifecycleService { + s.timeout = timeout + return s +} + +// MasterTimeout specifies the timeout for connection to master. +func (s *XPackIlmGetLifecycleService) MasterTimeout(masterTimeout string) *XPackIlmGetLifecycleService { + s.masterTimeout = masterTimeout + return s +} + +// FlatSettings is returns settings in flat format (default: false). +func (s *XPackIlmGetLifecycleService) FlatSettings(flatSettings bool) *XPackIlmGetLifecycleService { + s.flatSettings = &flatSettings + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackIlmGetLifecycleService) buildURL() (string, url.Values, error) { + // Build URL + var err error + var path string + if len(s.policy) > 0 { + path, err = uritemplates.Expand("/_ilm/policy/{policy}", map[string]string{ + "policy": strings.Join(s.policy, ","), + }) + } else { + path = "/_ilm/policy" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.flatSettings; v != nil { + params.Set("flat_settings", fmt.Sprint(*v)) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.local; v != nil { + params.Set("local", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackIlmGetLifecycleService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackIlmGetLifecycleService) Do(ctx context.Context) (map[string]*XPackIlmGetLifecycleResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + var ret map[string]*XPackIlmGetLifecycleResponse + if err := s.client.decoder.Decode(res.Body, &ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackIlmGetLifecycleResponse is the response of XPackIlmGetLifecycleService.Do. +type XPackIlmGetLifecycleResponse struct { + Version int `json:"version,omitempty"` + ModifiedDate string `json:"modified_date,omitempty"` // e.g. "2019-10-03T17:43:42.720Z" + Policy map[string]interface{} `json:"policy,omitempty"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_ilm_put_lifecycle.go b/vendor/github.com/olivere/elastic/v7/xpack_ilm_put_lifecycle.go new file mode 100644 index 0000000..f2e8ba1 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_ilm_put_lifecycle.go @@ -0,0 +1,214 @@ +// 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" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// See the documentation at +// https://www.elastic.co/guide/en/elasticsearch/reference/6.7/ilm-put-lifecycle.html +type XPackIlmPutLifecycleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + policy string + timeout string + masterTimeout string + flatSettings *bool + bodyJson interface{} + bodyString string +} + +// NewXPackIlmPutLifecycleService creates a new XPackIlmPutLifecycleService. +func NewXPackIlmPutLifecycleService(client *Client) *XPackIlmPutLifecycleService { + return &XPackIlmPutLifecycleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackIlmPutLifecycleService) Pretty(pretty bool) *XPackIlmPutLifecycleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackIlmPutLifecycleService) Human(human bool) *XPackIlmPutLifecycleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackIlmPutLifecycleService) ErrorTrace(errorTrace bool) *XPackIlmPutLifecycleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackIlmPutLifecycleService) FilterPath(filterPath ...string) *XPackIlmPutLifecycleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackIlmPutLifecycleService) Header(name string, value string) *XPackIlmPutLifecycleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackIlmPutLifecycleService) Headers(headers http.Header) *XPackIlmPutLifecycleService { + s.headers = headers + return s +} + +// Policy is the name of the index lifecycle policy. +func (s *XPackIlmPutLifecycleService) Policy(policy string) *XPackIlmPutLifecycleService { + s.policy = policy + return s +} + +// Timeout is an explicit operation timeout. +func (s *XPackIlmPutLifecycleService) Timeout(timeout string) *XPackIlmPutLifecycleService { + s.timeout = timeout + return s +} + +// MasterTimeout specifies the timeout for connection to master. +func (s *XPackIlmPutLifecycleService) MasterTimeout(masterTimeout string) *XPackIlmPutLifecycleService { + s.masterTimeout = masterTimeout + return s +} + +// FlatSettings indicates whether to return settings in flat format (default: false). +func (s *XPackIlmPutLifecycleService) FlatSettings(flatSettings bool) *XPackIlmPutLifecycleService { + s.flatSettings = &flatSettings + return s +} + +// BodyJson is documented as: The template definition. +func (s *XPackIlmPutLifecycleService) BodyJson(body interface{}) *XPackIlmPutLifecycleService { + s.bodyJson = body + return s +} + +// BodyString is documented as: The template definition. +func (s *XPackIlmPutLifecycleService) BodyString(body string) *XPackIlmPutLifecycleService { + s.bodyString = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackIlmPutLifecycleService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_ilm/policy/{policy}", map[string]string{ + "policy": s.policy, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.timeout != "" { + params.Set("timeout", s.timeout) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.flatSettings; v != nil { + params.Set("flat_settings", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackIlmPutLifecycleService) Validate() error { + var invalid []string + if s.policy == "" { + invalid = append(invalid, "Policy") + } + 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 *XPackIlmPutLifecycleService) Do(ctx context.Context) (*XPackIlmPutLifecycleResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackIlmPutLifecycleResponse) + if err := s.client.decoder.Decode(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackIlmPutLifecycleSResponse is the response of XPackIlmPutLifecycleService.Do. +type XPackIlmPutLifecycleResponse struct { + Acknowledged bool `json:"acknowledged"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_info.go b/vendor/github.com/olivere/elastic/v7/xpack_info.go new file mode 100644 index 0000000..d9cbeed --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_info.go @@ -0,0 +1,225 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackInfoService retrieves xpack info. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/info-api.html. +type XPackInfoService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers +} + +// NewXPackInfoService creates a new XPackInfoService. +func NewXPackInfoService(client *Client) *XPackInfoService { + return &XPackInfoService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackInfoService) Pretty(pretty bool) *XPackInfoService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackInfoService) Human(human bool) *XPackInfoService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackInfoService) ErrorTrace(errorTrace bool) *XPackInfoService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackInfoService) FilterPath(filterPath ...string) *XPackInfoService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackInfoService) Header(name string, value string) *XPackInfoService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackInfoService) Headers(headers http.Header) *XPackInfoService { + s.headers = headers + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackInfoService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_xpack", map[string]string{}) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackInfoService) Validate() error { + var invalid []string + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackInfoService) Do(ctx context.Context) (*XPackInfoServiceResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := XPackInfoServiceResponse{} + if err := json.Unmarshal(res.Body, &ret); err != nil { + return nil, err + } + return &ret, nil +} + +// XPackInfoServiceResponse is the response of XPackInfoService.Do. +type XPackInfoServiceResponse struct { + Build XPackInfoBuild `json:"build"` + License XPackInfoLicense `json:"license"` + Features XPackInfoFeatures `json:"features"` + Tagline string `json:"tagline"` +} + +// XPackInfoBuild is the xpack build info +type XPackInfoBuild struct { + Hash string `json:"hash"` + Date string `json:"date"` +} + +// XPackInfoLicense is the xpack license info +type XPackInfoLicense struct { + UID string `json:"uid"` + Type string `json:"type"` + Mode string `json:"mode"` + Status string `json:"status"` + ExpiryMilis int `json:"expiry_date_in_millis"` +} + +// XPackInfoFeatures is the xpack feature info object +type XPackInfoFeatures struct { + Graph XPackInfoGraph `json:"graph"` + Logstash XPackInfoLogstash `json:"logstash"` + MachineLearning XPackInfoML `json:"ml"` + Monitoring XPackInfoMonitoring `json:"monitoring"` + Rollup XPackInfoRollup `json:"rollup"` + Security XPackInfoSecurity `json:"security"` + Watcher XPackInfoWatcher `json:"watcher"` +} + +// XPackInfoGraph is the xpack graph plugin info +type XPackInfoGraph struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} + +// XPackInfoLogstash is the xpack logstash plugin info +type XPackInfoLogstash struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} + +// XPackInfoML is the xpack machine learning plugin info +type XPackInfoML struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` + NativeCodeInfo map[string]string `json:"native_code_info"` +} + +// XPackInfoMonitoring is the xpack monitoring plugin info +type XPackInfoMonitoring struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} + +// XPackInfoRollup is the xpack rollup plugin info +type XPackInfoRollup struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} + +// XPackInfoSecurity is the xpack security plugin info +type XPackInfoSecurity struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} + +// XPackInfoWatcher is the xpack watcher plugin info +type XPackInfoWatcher struct { + Description string `json:"description"` + Available bool `json:"available"` + Enabled bool `json:"enabled"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_change_password.go b/vendor/github.com/olivere/elastic/v7/xpack_security_change_password.go new file mode 100644 index 0000000..34174a1 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_change_password.go @@ -0,0 +1,201 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityChangePasswordService changes a native user's password. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.1/security-api-change-password.html. +type XPackSecurityChangePasswordService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + username string + password string + refresh string + body interface{} +} + +// NewXPackSecurityChangePasswordService creates a new XPackSecurityChangePasswordService. +func NewXPackSecurityChangePasswordService(client *Client) *XPackSecurityChangePasswordService { + return &XPackSecurityChangePasswordService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityChangePasswordService) Pretty(pretty bool) *XPackSecurityChangePasswordService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityChangePasswordService) Human(human bool) *XPackSecurityChangePasswordService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityChangePasswordService) ErrorTrace(errorTrace bool) *XPackSecurityChangePasswordService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityChangePasswordService) FilterPath(filterPath ...string) *XPackSecurityChangePasswordService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityChangePasswordService) Header(name string, value string) *XPackSecurityChangePasswordService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityChangePasswordService) Headers(headers http.Header) *XPackSecurityChangePasswordService { + s.headers = headers + return s +} + +// Username is name of the user to change. +func (s *XPackSecurityChangePasswordService) Username(username string) *XPackSecurityChangePasswordService { + s.username = username + return s +} + +// Password is the new value of the password. +func (s *XPackSecurityChangePasswordService) Password(password string) *XPackSecurityChangePasswordService { + s.password = password + return s +} + +// Refresh, if "true" (the default), refreshes the affected shards to make this operation +// visible to search, if "wait_for" then wait for a refresh to make this operation visible +// to search, if "false" then do nothing with refreshes. +func (s *XPackSecurityChangePasswordService) Refresh(refresh string) *XPackSecurityChangePasswordService { + s.refresh = refresh + return s +} + +// Body specifies the password. Use a string or a type that will get serialized as JSON. +func (s *XPackSecurityChangePasswordService) Body(body interface{}) *XPackSecurityChangePasswordService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityChangePasswordService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_xpack/security/user/{username}/_password", map[string]string{ + "username": s.username, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.refresh; v != "" { + params.Set("refresh", v) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityChangePasswordService) Validate() error { + var invalid []string + if s.username == "" { + invalid = append(invalid, "Userame") + } + if s.password == "" && s.body == nil { + invalid = append(invalid, "Body") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityChangePasswordService) Do(ctx context.Context) (*XPackSecurityChangeUserPasswordResponse, 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 + } + + var body interface{} + if s.body != nil { + body = s.body + } else { + body = map[string]interface{}{ + "password": s.password, + } + } + + // Get HTTP response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityChangeUserPasswordResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityChangeUserPasswordResponse is the response of +// XPackSecurityChangePasswordService.Do. +// +// A successful call returns an empty JSON structure: {}. +type XPackSecurityChangeUserPasswordResponse struct { +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role.go b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role.go new file mode 100644 index 0000000..d9c7cb9 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role.go @@ -0,0 +1,159 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityDeleteRoleService delete a role by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-delete-role.html. +type XPackSecurityDeleteRoleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string +} + +// NewXPackSecurityDeleteRoleService creates a new XPackSecurityDeleteRoleService. +func NewXPackSecurityDeleteRoleService(client *Client) *XPackSecurityDeleteRoleService { + return &XPackSecurityDeleteRoleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityDeleteRoleService) Pretty(pretty bool) *XPackSecurityDeleteRoleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityDeleteRoleService) Human(human bool) *XPackSecurityDeleteRoleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityDeleteRoleService) ErrorTrace(errorTrace bool) *XPackSecurityDeleteRoleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityDeleteRoleService) FilterPath(filterPath ...string) *XPackSecurityDeleteRoleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityDeleteRoleService) Header(name string, value string) *XPackSecurityDeleteRoleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityDeleteRoleService) Headers(headers http.Header) *XPackSecurityDeleteRoleService { + s.headers = headers + return s +} + +// Name is name of the role to delete. +func (s *XPackSecurityDeleteRoleService) Name(name string) *XPackSecurityDeleteRoleService { + s.name = name + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityDeleteRoleService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityDeleteRoleService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityDeleteRoleService) Do(ctx context.Context) (*XPackSecurityDeleteRoleResponse, 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, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityDeleteRoleResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityDeleteRoleResponse is the response of XPackSecurityDeleteRoleService.Do. +type XPackSecurityDeleteRoleResponse struct { + Found bool `json:"found"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role_mapping.go b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role_mapping.go new file mode 100644 index 0000000..05b564b --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_role_mapping.go @@ -0,0 +1,159 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityDeleteRoleMappingService delete a role mapping by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-delete-role-mapping.html. +type XPackSecurityDeleteRoleMappingService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string +} + +// NewXPackSecurityDeleteRoleMappingService creates a new XPackSecurityDeleteRoleMappingService. +func NewXPackSecurityDeleteRoleMappingService(client *Client) *XPackSecurityDeleteRoleMappingService { + return &XPackSecurityDeleteRoleMappingService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityDeleteRoleMappingService) Pretty(pretty bool) *XPackSecurityDeleteRoleMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityDeleteRoleMappingService) Human(human bool) *XPackSecurityDeleteRoleMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityDeleteRoleMappingService) ErrorTrace(errorTrace bool) *XPackSecurityDeleteRoleMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityDeleteRoleMappingService) FilterPath(filterPath ...string) *XPackSecurityDeleteRoleMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityDeleteRoleMappingService) Header(name string, value string) *XPackSecurityDeleteRoleMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityDeleteRoleMappingService) Headers(headers http.Header) *XPackSecurityDeleteRoleMappingService { + s.headers = headers + return s +} + +// Name is name of the role mapping to delete. +func (s *XPackSecurityDeleteRoleMappingService) Name(name string) *XPackSecurityDeleteRoleMappingService { + s.name = name + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityDeleteRoleMappingService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role_mapping/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityDeleteRoleMappingService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityDeleteRoleMappingService) Do(ctx context.Context) (*XPackSecurityDeleteRoleMappingResponse, 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, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityDeleteRoleMappingResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityDeleteRoleMappingResponse is the response of XPackSecurityDeleteRoleMappingService.Do. +type XPackSecurityDeleteRoleMappingResponse struct { + Found bool `json:"found"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_delete_user.go b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_user.go new file mode 100644 index 0000000..1e079f7 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_delete_user.go @@ -0,0 +1,170 @@ +// Copyright 2012-2019 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityDeleteUserService delete a user by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/security-api-delete-user.html. +type XPackSecurityDeleteUserService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + username string + refresh string +} + +// NewXPackSecurityDeleteUserService creates a new XPackSecurityDeleteUserService. +func NewXPackSecurityDeleteUserService(client *Client) *XPackSecurityDeleteUserService { + return &XPackSecurityDeleteUserService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityDeleteUserService) Pretty(pretty bool) *XPackSecurityDeleteUserService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityDeleteUserService) Human(human bool) *XPackSecurityDeleteUserService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityDeleteUserService) ErrorTrace(errorTrace bool) *XPackSecurityDeleteUserService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityDeleteUserService) FilterPath(filterPath ...string) *XPackSecurityDeleteUserService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityDeleteUserService) Header(name string, value string) *XPackSecurityDeleteUserService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityDeleteUserService) Headers(headers http.Header) *XPackSecurityDeleteUserService { + s.headers = headers + return s +} + +// Username is name of the user to delete. +func (s *XPackSecurityDeleteUserService) Username(username string) *XPackSecurityDeleteUserService { + s.username = username + return s +} + +// Refresh specifies if and how to wait for refreshing the shards after the request. +// Possible values are "true" (default), "false" and "wait_for", all of type string. +func (s *XPackSecurityDeleteUserService) Refresh(refresh string) *XPackSecurityDeleteUserService { + s.refresh = refresh + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityDeleteUserService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/user/{username}", map[string]string{ + "username": s.username, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.refresh; v != "" { + params.Set("refresh", v) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityDeleteUserService) Validate() error { + var invalid []string + if s.username == "" { + invalid = append(invalid, "Username") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityDeleteUserService) Do(ctx context.Context) (*XPackSecurityDeleteUserResponse, 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, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityDeleteUserResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityDeleteUserResponse is the response of XPackSecurityDeleteUserService.Do. +type XPackSecurityDeleteUserResponse struct { + Found bool `json:"found"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_disable_user.go b/vendor/github.com/olivere/elastic/v7/xpack_security_disable_user.go new file mode 100644 index 0000000..846c0e2 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_disable_user.go @@ -0,0 +1,168 @@ +// Copyright 2012-2019 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityDisableUserService retrieves a user by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-user.html. +type XPackSecurityDisableUserService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + username string + refresh string +} + +// NewXPackSecurityDisableUserService creates a new XPackSecurityDisableUserService. +func NewXPackSecurityDisableUserService(client *Client) *XPackSecurityDisableUserService { + return &XPackSecurityDisableUserService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityDisableUserService) Pretty(pretty bool) *XPackSecurityDisableUserService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityDisableUserService) Human(human bool) *XPackSecurityDisableUserService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityDisableUserService) ErrorTrace(errorTrace bool) *XPackSecurityDisableUserService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityDisableUserService) FilterPath(filterPath ...string) *XPackSecurityDisableUserService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityDisableUserService) Header(name string, value string) *XPackSecurityDisableUserService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityDisableUserService) Headers(headers http.Header) *XPackSecurityDisableUserService { + s.headers = headers + return s +} + +// Username is name of the user to disable. +func (s *XPackSecurityDisableUserService) Username(username string) *XPackSecurityDisableUserService { + s.username = username + return s +} + +// Refresh specifies if and how to wait for refreshing the shards after the request. +// Possible values are "true" (default), "false" and "wait_for", all of type string. +func (s *XPackSecurityDisableUserService) Refresh(refresh string) *XPackSecurityDisableUserService { + s.refresh = refresh + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityDisableUserService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/user/{username}/_disable", map[string]string{ + "username": s.username, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.refresh; v != "" { + params.Set("refresh", v) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityDisableUserService) Validate() error { + var invalid []string + if s.username == "" { + invalid = append(invalid, "Username") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityDisableUserService) Do(ctx context.Context) (*XPackSecurityDisableUserResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityDisableUserResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityDisableUserResponse is the response of XPackSecurityDisableUserService.Do. +type XPackSecurityDisableUserResponse struct { +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_enable_user.go b/vendor/github.com/olivere/elastic/v7/xpack_security_enable_user.go new file mode 100644 index 0000000..c04b917 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_enable_user.go @@ -0,0 +1,168 @@ +// Copyright 2012-2019 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityEnableUserService retrieves a user by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-user.html. +type XPackSecurityEnableUserService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + username string + refresh string +} + +// NewXPackSecurityEnableUserService creates a new XPackSecurityEnableUserService. +func NewXPackSecurityEnableUserService(client *Client) *XPackSecurityEnableUserService { + return &XPackSecurityEnableUserService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityEnableUserService) Pretty(pretty bool) *XPackSecurityEnableUserService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityEnableUserService) Human(human bool) *XPackSecurityEnableUserService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityEnableUserService) ErrorTrace(errorTrace bool) *XPackSecurityEnableUserService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityEnableUserService) FilterPath(filterPath ...string) *XPackSecurityEnableUserService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityEnableUserService) Header(name string, value string) *XPackSecurityEnableUserService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityEnableUserService) Headers(headers http.Header) *XPackSecurityEnableUserService { + s.headers = headers + return s +} + +// Username is name of the user to enable. +func (s *XPackSecurityEnableUserService) Username(username string) *XPackSecurityEnableUserService { + s.username = username + return s +} + +// Refresh specifies if and how to wait for refreshing the shards after the request. +// Possible values are "true" (default), "false" and "wait_for", all of type string. +func (s *XPackSecurityEnableUserService) Refresh(refresh string) *XPackSecurityEnableUserService { + s.refresh = refresh + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityEnableUserService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/user/{username}/_enable", map[string]string{ + "username": s.username, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.refresh; v != "" { + params.Set("refresh", v) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityEnableUserService) Validate() error { + var invalid []string + if s.username == "" { + invalid = append(invalid, "Username") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityEnableUserService) Do(ctx context.Context) (*XPackSecurityEnableUserResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityEnableUserResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityEnableUserResponse is the response of XPackSecurityEnableUserService.Do. +type XPackSecurityEnableUserResponse struct { +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_get_role.go b/vendor/github.com/olivere/elastic/v7/xpack_security_get_role.go new file mode 100644 index 0000000..c2ab0fd --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_get_role.go @@ -0,0 +1,186 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityGetRoleService retrieves a role by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-role.html. +type XPackSecurityGetRoleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string +} + +// NewXPackSecurityGetRoleService creates a new XPackSecurityGetRoleService. +func NewXPackSecurityGetRoleService(client *Client) *XPackSecurityGetRoleService { + return &XPackSecurityGetRoleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityGetRoleService) Pretty(pretty bool) *XPackSecurityGetRoleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityGetRoleService) Human(human bool) *XPackSecurityGetRoleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityGetRoleService) ErrorTrace(errorTrace bool) *XPackSecurityGetRoleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityGetRoleService) FilterPath(filterPath ...string) *XPackSecurityGetRoleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityGetRoleService) Header(name string, value string) *XPackSecurityGetRoleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityGetRoleService) Headers(headers http.Header) *XPackSecurityGetRoleService { + s.headers = headers + return s +} + +// Name is name of the role to retrieve. +func (s *XPackSecurityGetRoleService) Name(name string) *XPackSecurityGetRoleService { + s.name = name + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityGetRoleService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityGetRoleService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityGetRoleService) Do(ctx context.Context) (*XPackSecurityGetRoleResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := XPackSecurityGetRoleResponse{} + if err := json.Unmarshal(res.Body, &ret); err != nil { + return nil, err + } + return &ret, nil +} + +// XPackSecurityGetRoleResponse is the response of XPackSecurityGetRoleService.Do. +type XPackSecurityGetRoleResponse map[string]XPackSecurityRole + +// XPackSecurityRole is the role object. +// +// The Java source for this struct is defined here: +// https://github.com/elastic/elasticsearch/blob/6.7/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/RoleDescriptor.java +type XPackSecurityRole struct { + Cluster []string `json:"cluster"` + Indices []XPackSecurityIndicesPermissions `json:"indices"` + Applications []XPackSecurityApplicationPrivileges `json:"applications"` + RunAs []string `json:"run_as"` + Global map[string]interface{} `json:"global"` + Metadata map[string]interface{} `json:"metadata"` + TransientMetadata map[string]interface{} `json:"transient_metadata"` +} + +// XPackSecurityApplicationPrivileges is the application privileges object +type XPackSecurityApplicationPrivileges struct { + Application string `json:"application"` + Privileges []string `json:"privileges"` + Ressources []string `json:"resources"` +} + +// XPackSecurityIndicesPermissions is the indices permission object +type XPackSecurityIndicesPermissions struct { + Names []string `json:"names"` + Privileges []string `json:"privileges"` + FieldSecurity interface{} `json:"field_security,omitempty"` + Query string `json:"query"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_get_role_mapping.go b/vendor/github.com/olivere/elastic/v7/xpack_security_get_role_mapping.go new file mode 100644 index 0000000..24230be --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_get_role_mapping.go @@ -0,0 +1,165 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityGetRoleMappingService retrieves a role mapping by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-role-mapping.html. +type XPackSecurityGetRoleMappingService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string +} + +// NewXPackSecurityGetRoleMappingService creates a new XPackSecurityGetRoleMappingService. +func NewXPackSecurityGetRoleMappingService(client *Client) *XPackSecurityGetRoleMappingService { + return &XPackSecurityGetRoleMappingService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityGetRoleMappingService) Pretty(pretty bool) *XPackSecurityGetRoleMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityGetRoleMappingService) Human(human bool) *XPackSecurityGetRoleMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityGetRoleMappingService) ErrorTrace(errorTrace bool) *XPackSecurityGetRoleMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityGetRoleMappingService) FilterPath(filterPath ...string) *XPackSecurityGetRoleMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityGetRoleMappingService) Header(name string, value string) *XPackSecurityGetRoleMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityGetRoleMappingService) Headers(headers http.Header) *XPackSecurityGetRoleMappingService { + s.headers = headers + return s +} + +// Name is name of the role mapping to retrieve. +func (s *XPackSecurityGetRoleMappingService) Name(name string) *XPackSecurityGetRoleMappingService { + s.name = name + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityGetRoleMappingService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role_mapping/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityGetRoleMappingService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityGetRoleMappingService) Do(ctx context.Context) (*XPackSecurityGetRoleMappingResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := XPackSecurityGetRoleMappingResponse{} + if err := json.Unmarshal(res.Body, &ret); err != nil { + return nil, err + } + return &ret, nil +} + +// XPackSecurityGetRoleMappingResponse is the response of XPackSecurityGetRoleMappingService.Do. +type XPackSecurityGetRoleMappingResponse map[string]XPackSecurityRoleMapping + +// XPackSecurityRoleMapping is the role mapping object +type XPackSecurityRoleMapping struct { + Enabled bool `json:"enabled"` + Roles []string `json:"roles"` + Rules map[string]interface{} `json:"rules"` + Metadata interface{} `json:"metadata"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_get_user.go b/vendor/github.com/olivere/elastic/v7/xpack_security_get_user.go new file mode 100644 index 0000000..50a179b --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_get_user.go @@ -0,0 +1,176 @@ +// Copyright 2012-2019 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityGetUserService retrieves a user by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-user.html. +type XPackSecurityGetUserService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + usernames []string +} + +// NewXPackSecurityGetUserService creates a new XPackSecurityGetUserService. +func NewXPackSecurityGetUserService(client *Client) *XPackSecurityGetUserService { + return &XPackSecurityGetUserService{ + client: client, + } +} + +// Pretty indicates that the JSON response be indented and human readable. +func (s *XPackSecurityGetUserService) Pretty(pretty bool) *XPackSecurityGetUserService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityGetUserService) Human(human bool) *XPackSecurityGetUserService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityGetUserService) ErrorTrace(errorTrace bool) *XPackSecurityGetUserService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityGetUserService) FilterPath(filterPath ...string) *XPackSecurityGetUserService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityGetUserService) Header(name string, value string) *XPackSecurityGetUserService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityGetUserService) Headers(headers http.Header) *XPackSecurityGetUserService { + s.headers = headers + return s +} + +// Usernames are the names of one or more users to retrieve. +func (s *XPackSecurityGetUserService) Usernames(usernames ...string) *XPackSecurityGetUserService { + for _, username := range usernames { + if v := strings.TrimSpace(username); v != "" { + s.usernames = append(s.usernames, v) + } + } + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityGetUserService) buildURL() (string, url.Values, error) { + // Build URL + var ( + path string + err error + ) + if len(s.usernames) > 0 { + path, err = uritemplates.Expand("/_security/user/{username}", map[string]string{ + "username": strings.Join(s.usernames, ","), + }) + } else { + path = "/_security/user" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityGetUserService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackSecurityGetUserService) Do(ctx context.Context) (*XPackSecurityGetUserResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := XPackSecurityGetUserResponse{} + if err := json.Unmarshal(res.Body, &ret); err != nil { + return nil, err + } + return &ret, nil +} + +// XPackSecurityGetUserResponse is the response of XPackSecurityGetUserService.Do. +type XPackSecurityGetUserResponse map[string]XPackSecurityUser + +// XPackSecurityUser is the user object. +// +// The Java source for this struct is defined here: +// https://github.com/elastic/elasticsearch/blob/7.3/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/user/User.java +type XPackSecurityUser struct { + Username string `json:"username"` + Roles []string `json:"roles"` + Fullname string `json:"full_name"` + Email string `json:"email"` + Metadata map[string]interface{} `json:"metadata"` + Enabled bool `json:"enabled"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_put_role.go b/vendor/github.com/olivere/elastic/v7/xpack_security_put_role.go new file mode 100644 index 0000000..f3c869f --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_put_role.go @@ -0,0 +1,174 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityPutRoleService retrieves a role by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-put-role.html. +type XPackSecurityPutRoleService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string + body interface{} +} + +// NewXPackSecurityPutRoleService creates a new XPackSecurityPutRoleService. +func NewXPackSecurityPutRoleService(client *Client) *XPackSecurityPutRoleService { + return &XPackSecurityPutRoleService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityPutRoleService) Pretty(pretty bool) *XPackSecurityPutRoleService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityPutRoleService) Human(human bool) *XPackSecurityPutRoleService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityPutRoleService) ErrorTrace(errorTrace bool) *XPackSecurityPutRoleService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityPutRoleService) FilterPath(filterPath ...string) *XPackSecurityPutRoleService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityPutRoleService) Header(name string, value string) *XPackSecurityPutRoleService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityPutRoleService) Headers(headers http.Header) *XPackSecurityPutRoleService { + s.headers = headers + return s +} + +// Name is name of the role to create. +func (s *XPackSecurityPutRoleService) Name(name string) *XPackSecurityPutRoleService { + s.name = name + return s +} + +// Body specifies the role. Use a string or a type that will get serialized as JSON. +func (s *XPackSecurityPutRoleService) Body(body interface{}) *XPackSecurityPutRoleService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityPutRoleService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityPutRoleService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if s.body == nil { + invalid = append(invalid, "Body") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityPutRoleService) Do(ctx context.Context) (*XPackSecurityPutRoleResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: s.body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityPutRoleResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityPutRoleResponse is the response of XPackSecurityPutRoleService.Do. +type XPackSecurityPutRoleResponse struct { + Role XPackSecurityPutRole +} + +type XPackSecurityPutRole struct { + Created bool `json:"created"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_put_role_mapping.go b/vendor/github.com/olivere/elastic/v7/xpack_security_put_role_mapping.go new file mode 100644 index 0000000..0850d5e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_put_role_mapping.go @@ -0,0 +1,174 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityPutRoleMappingService create or update a role mapping by its name. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-put-role-mapping.html. +type XPackSecurityPutRoleMappingService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + name string + body interface{} +} + +// NewXPackSecurityPutRoleMappingService creates a new XPackSecurityPutRoleMappingService. +func NewXPackSecurityPutRoleMappingService(client *Client) *XPackSecurityPutRoleMappingService { + return &XPackSecurityPutRoleMappingService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityPutRoleMappingService) Pretty(pretty bool) *XPackSecurityPutRoleMappingService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityPutRoleMappingService) Human(human bool) *XPackSecurityPutRoleMappingService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityPutRoleMappingService) ErrorTrace(errorTrace bool) *XPackSecurityPutRoleMappingService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityPutRoleMappingService) FilterPath(filterPath ...string) *XPackSecurityPutRoleMappingService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityPutRoleMappingService) Header(name string, value string) *XPackSecurityPutRoleMappingService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityPutRoleMappingService) Headers(headers http.Header) *XPackSecurityPutRoleMappingService { + s.headers = headers + return s +} + +// Name is name of the role mapping to create/update. +func (s *XPackSecurityPutRoleMappingService) Name(name string) *XPackSecurityPutRoleMappingService { + s.name = name + return s +} + +// Body specifies the role mapping. Use a string or a type that will get serialized as JSON. +func (s *XPackSecurityPutRoleMappingService) Body(body interface{}) *XPackSecurityPutRoleMappingService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityPutRoleMappingService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/role_mapping/{name}", map[string]string{ + "name": s.name, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityPutRoleMappingService) Validate() error { + var invalid []string + if s.name == "" { + invalid = append(invalid, "Name") + } + if s.body == nil { + invalid = append(invalid, "Body") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityPutRoleMappingService) Do(ctx context.Context) (*XPackSecurityPutRoleMappingResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: s.body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityPutRoleMappingResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityPutRoleMappingResponse is the response of XPackSecurityPutRoleMappingService.Do. +type XPackSecurityPutRoleMappingResponse struct { + Role_Mapping XPackSecurityPutRoleMapping +} + +type XPackSecurityPutRoleMapping struct { + Created bool `json:"created"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_security_put_user.go b/vendor/github.com/olivere/elastic/v7/xpack_security_put_user.go new file mode 100644 index 0000000..f7ab77e --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_security_put_user.go @@ -0,0 +1,215 @@ +// Copyright 2012-2019 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackSecurityPutUserService adds a user. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/security-api-put-user.html. +type XPackSecurityPutUserService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + username string + refresh string + + user *XPackSecurityPutUserRequest + body interface{} +} + +// NewXPackSecurityPutUserService creates a new XPackSecurityPutUserService. +func NewXPackSecurityPutUserService(client *Client) *XPackSecurityPutUserService { + return &XPackSecurityPutUserService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackSecurityPutUserService) Pretty(pretty bool) *XPackSecurityPutUserService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackSecurityPutUserService) Human(human bool) *XPackSecurityPutUserService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackSecurityPutUserService) ErrorTrace(errorTrace bool) *XPackSecurityPutUserService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackSecurityPutUserService) FilterPath(filterPath ...string) *XPackSecurityPutUserService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackSecurityPutUserService) Header(name string, value string) *XPackSecurityPutUserService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackSecurityPutUserService) Headers(headers http.Header) *XPackSecurityPutUserService { + s.headers = headers + return s +} + +// Username is the name of the user to add. +func (s *XPackSecurityPutUserService) Username(username string) *XPackSecurityPutUserService { + s.username = username + return s +} + +// User specifies the data of the new user. +// +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.4/security-api-put-user.html +// for details. +func (s *XPackSecurityPutUserService) User(user *XPackSecurityPutUserRequest) *XPackSecurityPutUserService { + s.user = user + return s +} + +// Refresh specifies if and how to wait for refreshing the shards after the request. +// Possible values are "true" (default), "false" and "wait_for", all of type string. +func (s *XPackSecurityPutUserService) Refresh(refresh string) *XPackSecurityPutUserService { + s.refresh = refresh + return s +} + +// Body specifies the user. Use a string or a type that will get serialized as JSON. +func (s *XPackSecurityPutUserService) Body(body interface{}) *XPackSecurityPutUserService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackSecurityPutUserService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_security/user/{username}", map[string]string{ + "username": s.username, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.refresh; v != "" { + params.Set("refresh", v) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackSecurityPutUserService) Validate() error { + var invalid []string + if s.username == "" { + invalid = append(invalid, "Username") + } + if s.user == nil && s.body == nil { + invalid = append(invalid, "User") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackSecurityPutUserService) Do(ctx context.Context) (*XPackSecurityPutUserResponse, 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 + } + + var body interface{} + if s.user != nil { + body = s.user + } else { + body = s.body + } + + // Get HTTP response + res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: body, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackSecurityPutUserResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackSecurityPutUserRequest specifies the data required/allowed to add +// a new user. +type XPackSecurityPutUserRequest struct { + Enabled bool `json:"enabled"` + Email string `json:"email,omitempty"` + FullName string `json:"full_name,omitempty"` + Metadata map[string]interface{} `json:"metadata,omitempty"` + Password string `json:"password,omitempty"` + PasswordHash string `json:"password_hash,omitempty"` + Roles []string `json:"roles"` +} + +// XPackSecurityPutUserResponse is the response of XPackSecurityPutUserService.Do. +type XPackSecurityPutUserResponse struct { + User XPackSecurityPutUser `json:"user"` +} + +// XPackSecurityPutUser is the response containing the creation information +type XPackSecurityPutUser struct { + Created bool `json:"created"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_ack_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_ack_watch.go new file mode 100644 index 0000000..d1ae925 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_ack_watch.go @@ -0,0 +1,198 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherAckWatchService enables you to manually throttle execution of the watch’s actions. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-ack-watch.html. +type XPackWatcherAckWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + watchId string + actionId []string + masterTimeout string +} + +// NewXPackWatcherAckWatchService creates a new XPackWatcherAckWatchService. +func NewXPackWatcherAckWatchService(client *Client) *XPackWatcherAckWatchService { + return &XPackWatcherAckWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherAckWatchService) Pretty(pretty bool) *XPackWatcherAckWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherAckWatchService) Human(human bool) *XPackWatcherAckWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherAckWatchService) ErrorTrace(errorTrace bool) *XPackWatcherAckWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherAckWatchService) FilterPath(filterPath ...string) *XPackWatcherAckWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherAckWatchService) Header(name string, value string) *XPackWatcherAckWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherAckWatchService) Headers(headers http.Header) *XPackWatcherAckWatchService { + s.headers = headers + return s +} + +// WatchId is the unique ID of the watch. +func (s *XPackWatcherAckWatchService) WatchId(watchId string) *XPackWatcherAckWatchService { + s.watchId = watchId + return s +} + +// ActionId is a slice of action ids to be acked. +func (s *XPackWatcherAckWatchService) ActionId(actionId ...string) *XPackWatcherAckWatchService { + s.actionId = append(s.actionId, actionId...) + return s +} + +// MasterTimeout indicates an explicit operation timeout for +// connection to master node. +func (s *XPackWatcherAckWatchService) MasterTimeout(masterTimeout string) *XPackWatcherAckWatchService { + s.masterTimeout = masterTimeout + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherAckWatchService) buildURL() (string, url.Values, error) { + // Build URL + var ( + path string + err error + ) + if len(s.actionId) > 0 { + path, err = uritemplates.Expand("/_watcher/watch/{watch_id}/_ack/{action_id}", map[string]string{ + "watch_id": s.watchId, + "action_id": strings.Join(s.actionId, ","), + }) + } else { + path, err = uritemplates.Expand("/_watcher/watch/{watch_id}/_ack", map[string]string{ + "watch_id": s.watchId, + }) + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherAckWatchService) Validate() error { + var invalid []string + if s.watchId == "" { + invalid = append(invalid, "WatchId") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackWatcherAckWatchService) Do(ctx context.Context) (*XPackWatcherAckWatchResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherAckWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherAckWatchResponse is the response of XPackWatcherAckWatchService.Do. +type XPackWatcherAckWatchResponse struct { + Status *XPackWatcherAckWatchStatus `json:"status"` +} + +// XPackWatcherAckWatchStatus is the status of a XPackWatcherAckWatchResponse. +type XPackWatcherAckWatchStatus struct { + State map[string]interface{} `json:"state"` + LastChecked string `json:"last_checked"` + LastMetCondition string `json:"last_met_condition"` + Actions map[string]map[string]interface{} `json:"actions"` + ExecutionState string `json:"execution_state"` + Version int `json:"version"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_activate_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_activate_watch.go new file mode 100644 index 0000000..9a49605 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_activate_watch.go @@ -0,0 +1,169 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherActivateWatchService enables you to activate a currently inactive watch. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-activate-watch.html. +type XPackWatcherActivateWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + watchId string + masterTimeout string +} + +// NewXPackWatcherActivateWatchService creates a new XPackWatcherActivateWatchService. +func NewXPackWatcherActivateWatchService(client *Client) *XPackWatcherActivateWatchService { + return &XPackWatcherActivateWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherActivateWatchService) Pretty(pretty bool) *XPackWatcherActivateWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherActivateWatchService) Human(human bool) *XPackWatcherActivateWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherActivateWatchService) ErrorTrace(errorTrace bool) *XPackWatcherActivateWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherActivateWatchService) FilterPath(filterPath ...string) *XPackWatcherActivateWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherActivateWatchService) Header(name string, value string) *XPackWatcherActivateWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherActivateWatchService) Headers(headers http.Header) *XPackWatcherActivateWatchService { + s.headers = headers + return s +} + +// WatchId is the ID of the watch to activate. +func (s *XPackWatcherActivateWatchService) WatchId(watchId string) *XPackWatcherActivateWatchService { + s.watchId = watchId + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *XPackWatcherActivateWatchService) MasterTimeout(masterTimeout string) *XPackWatcherActivateWatchService { + s.masterTimeout = masterTimeout + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherActivateWatchService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_watcher/watch/{watch_id}/_activate", map[string]string{ + "watch_id": s.watchId, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherActivateWatchService) Validate() error { + var invalid []string + if s.watchId == "" { + invalid = append(invalid, "WatchId") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackWatcherActivateWatchService) Do(ctx context.Context) (*XPackWatcherActivateWatchResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherActivateWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherActivateWatchResponse is the response of XPackWatcherActivateWatchService.Do. +type XPackWatcherActivateWatchResponse struct { + Status *XPackWatchStatus `json:"status"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_deactivate_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_deactivate_watch.go new file mode 100644 index 0000000..42c5e55 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_deactivate_watch.go @@ -0,0 +1,169 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherDeactivateWatchService enables you to deactivate a currently active watch. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-deactivate-watch.html. +type XPackWatcherDeactivateWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + watchId string + masterTimeout string +} + +// NewXPackWatcherDeactivateWatchService creates a new XPackWatcherDeactivateWatchService. +func NewXPackWatcherDeactivateWatchService(client *Client) *XPackWatcherDeactivateWatchService { + return &XPackWatcherDeactivateWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherDeactivateWatchService) Pretty(pretty bool) *XPackWatcherDeactivateWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherDeactivateWatchService) Human(human bool) *XPackWatcherDeactivateWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherDeactivateWatchService) ErrorTrace(errorTrace bool) *XPackWatcherDeactivateWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherDeactivateWatchService) FilterPath(filterPath ...string) *XPackWatcherDeactivateWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherDeactivateWatchService) Header(name string, value string) *XPackWatcherDeactivateWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherDeactivateWatchService) Headers(headers http.Header) *XPackWatcherDeactivateWatchService { + s.headers = headers + return s +} + +// WatchId is the ID of the watch to deactivate. +func (s *XPackWatcherDeactivateWatchService) WatchId(watchId string) *XPackWatcherDeactivateWatchService { + s.watchId = watchId + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *XPackWatcherDeactivateWatchService) MasterTimeout(masterTimeout string) *XPackWatcherDeactivateWatchService { + s.masterTimeout = masterTimeout + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherDeactivateWatchService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_watcher/watch/{watch_id}/_deactivate", map[string]string{ + "watch_id": s.watchId, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherDeactivateWatchService) Validate() error { + var invalid []string + if s.watchId == "" { + invalid = append(invalid, "WatchId") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackWatcherDeactivateWatchService) Do(ctx context.Context) (*XPackWatcherDeactivateWatchResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherDeactivateWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherDeactivateWatchResponse is the response of XPackWatcherDeactivateWatchService.Do. +type XPackWatcherDeactivateWatchResponse struct { + Status *XPackWatchStatus `json:"status"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_delete_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_delete_watch.go new file mode 100644 index 0000000..dc7e7f9 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_delete_watch.go @@ -0,0 +1,171 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherDeleteWatchService removes a watch. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-delete-watch.html. +type XPackWatcherDeleteWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + id string + masterTimeout string +} + +// NewXPackWatcherDeleteWatchService creates a new XPackWatcherDeleteWatchService. +func NewXPackWatcherDeleteWatchService(client *Client) *XPackWatcherDeleteWatchService { + return &XPackWatcherDeleteWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherDeleteWatchService) Pretty(pretty bool) *XPackWatcherDeleteWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherDeleteWatchService) Human(human bool) *XPackWatcherDeleteWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherDeleteWatchService) ErrorTrace(errorTrace bool) *XPackWatcherDeleteWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherDeleteWatchService) FilterPath(filterPath ...string) *XPackWatcherDeleteWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherDeleteWatchService) Header(name string, value string) *XPackWatcherDeleteWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherDeleteWatchService) Headers(headers http.Header) *XPackWatcherDeleteWatchService { + s.headers = headers + return s +} + +// Id of the watch to delete. +func (s *XPackWatcherDeleteWatchService) Id(id string) *XPackWatcherDeleteWatchService { + s.id = id + return s +} + +// MasterTimeout specifies an explicit operation timeout for connection to master node. +func (s *XPackWatcherDeleteWatchService) MasterTimeout(masterTimeout string) *XPackWatcherDeleteWatchService { + s.masterTimeout = masterTimeout + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherDeleteWatchService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_watcher/watch/{id}", map[string]string{ + "id": s.id, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherDeleteWatchService) 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 *XPackWatcherDeleteWatchService) Do(ctx context.Context) (*XPackWatcherDeleteWatchResponse, 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, PerformRequestOptions{ + Method: "DELETE", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherDeleteWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherDeleteWatchResponse is the response of XPackWatcherDeleteWatchService.Do. +type XPackWatcherDeleteWatchResponse struct { + Found bool `json:"found"` + Id string `json:"_id"` + Version int `json:"_version"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_execute_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_execute_watch.go new file mode 100644 index 0000000..9a31c51 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_execute_watch.go @@ -0,0 +1,214 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherExecuteWatchService forces the execution of a stored watch. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-execute-watch.html. +type XPackWatcherExecuteWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + id string + debug *bool + bodyJson interface{} + bodyString string +} + +// NewXPackWatcherExecuteWatchService creates a new XPackWatcherExecuteWatchService. +func NewXPackWatcherExecuteWatchService(client *Client) *XPackWatcherExecuteWatchService { + return &XPackWatcherExecuteWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherExecuteWatchService) Pretty(pretty bool) *XPackWatcherExecuteWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherExecuteWatchService) Human(human bool) *XPackWatcherExecuteWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherExecuteWatchService) ErrorTrace(errorTrace bool) *XPackWatcherExecuteWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherExecuteWatchService) FilterPath(filterPath ...string) *XPackWatcherExecuteWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherExecuteWatchService) Header(name string, value string) *XPackWatcherExecuteWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherExecuteWatchService) Headers(headers http.Header) *XPackWatcherExecuteWatchService { + s.headers = headers + return s +} + +// Id of the watch to execute on. +func (s *XPackWatcherExecuteWatchService) Id(id string) *XPackWatcherExecuteWatchService { + s.id = id + return s +} + +// Debug indicates whether the watch should execute in debug mode. +func (s *XPackWatcherExecuteWatchService) Debug(debug bool) *XPackWatcherExecuteWatchService { + s.debug = &debug + return s +} + +// BodyJson is documented as: Execution control. +func (s *XPackWatcherExecuteWatchService) BodyJson(body interface{}) *XPackWatcherExecuteWatchService { + s.bodyJson = body + return s +} + +// BodyString is documented as: Execution control. +func (s *XPackWatcherExecuteWatchService) BodyString(body string) *XPackWatcherExecuteWatchService { + s.bodyString = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherExecuteWatchService) buildURL() (string, url.Values, error) { + // Build URL + var ( + path string + err error + ) + if s.id != "" { + path, err = uritemplates.Expand("/_watcher/watch/{id}/_execute", map[string]string{ + "id": s.id, + }) + } else { + path = "/_watcher/watch/_execute" + } + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.debug; v != nil { + params.Set("debug", fmt.Sprint(*v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherExecuteWatchService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackWatcherExecuteWatchService) Do(ctx context.Context) (*XPackWatcherExecuteWatchResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherExecuteWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherExecuteWatchResponse is the response of XPackWatcherExecuteWatchService.Do. +type XPackWatcherExecuteWatchResponse struct { + Id string `json:"_id"` + WatchRecord *XPackWatchRecord `json:"watch_record"` +} + +type XPackWatchRecord struct { + WatchId string `json:"watch_id"` + Node string `json:"node"` + Messages []string `json:"messages"` + State string `json:"state"` + Status *XPackWatchRecordStatus `json:"status"` + Input map[string]map[string]interface{} `json:"input"` + Condition map[string]map[string]interface{} `json:"condition"` + Result map[string]interface{} `json:"Result"` +} + +type XPackWatchRecordStatus struct { + Version int `json:"version"` + State map[string]interface{} `json:"state"` + LastChecked string `json:"last_checked"` + LastMetCondition string `json:"last_met_condition"` + Actions map[string]map[string]interface{} `json:"actions"` + ExecutionState string `json:"execution_state"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_get_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_get_watch.go new file mode 100644 index 0000000..b0ce092 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_get_watch.go @@ -0,0 +1,214 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + "time" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherGetWatchService retrieves a watch by its ID. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-get-watch.html. +type XPackWatcherGetWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + id string +} + +// NewXPackWatcherGetWatchService creates a new XPackWatcherGetWatchService. +func NewXPackWatcherGetWatchService(client *Client) *XPackWatcherGetWatchService { + return &XPackWatcherGetWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherGetWatchService) Pretty(pretty bool) *XPackWatcherGetWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherGetWatchService) Human(human bool) *XPackWatcherGetWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherGetWatchService) ErrorTrace(errorTrace bool) *XPackWatcherGetWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherGetWatchService) FilterPath(filterPath ...string) *XPackWatcherGetWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherGetWatchService) Header(name string, value string) *XPackWatcherGetWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherGetWatchService) Headers(headers http.Header) *XPackWatcherGetWatchService { + s.headers = headers + return s +} + +// Id is ID of the watch to retrieve. +func (s *XPackWatcherGetWatchService) Id(id string) *XPackWatcherGetWatchService { + s.id = id + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherGetWatchService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_watcher/watch/{id}", map[string]string{ + "id": s.id, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherGetWatchService) 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 *XPackWatcherGetWatchService) Do(ctx context.Context) (*XPackWatcherGetWatchResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherGetWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherGetWatchResponse is the response of XPackWatcherGetWatchService.Do. +type XPackWatcherGetWatchResponse struct { + Found bool `json:"found"` + Id string `json:"_id"` + Version int64 `json:"_version,omitempty"` + Status *XPackWatchStatus `json:"status,omitempty"` + Watch *XPackWatch `json:"watch,omitempty"` +} + +type XPackWatchStatus struct { + State *XPackWatchExecutionState `json:"state,omitempty"` + LastChecked *time.Time `json:"last_checked,omitempty"` + LastMetCondition *time.Time `json:"last_met_condition,omitempty"` + Actions map[string]*XPackWatchActionStatus `json:"actions,omitempty"` + ExecutionState string `json:"execution_state,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + Version int64 `json:"version"` +} + +type XPackWatchExecutionState struct { + Active bool `json:"active"` + Timestamp time.Time `json:"timestamp"` +} + +type XPackWatchActionStatus struct { + AckStatus *XPackWatchActionAckStatus `json:"ack"` + LastExecution *XPackWatchActionExecutionState `json:"last_execution,omitempty"` + LastSuccessfulExecution *XPackWatchActionExecutionState `json:"last_successful_execution,omitempty"` + LastThrottle *XPackWatchActionThrottle `json:"last_throttle,omitempty"` +} + +type XPackWatchActionAckStatus struct { + Timestamp time.Time `json:"timestamp"` + AckStatusState string `json:"ack_status_state"` +} + +type XPackWatchActionExecutionState struct { + Timestamp time.Time `json:"timestamp"` + Successful bool `json:"successful"` + Reason string `json:"reason,omitempty"` +} + +type XPackWatchActionThrottle struct { + Timestamp time.Time `json:"timestamp"` + Reason string `json:"reason,omitempty"` +} + +type XPackWatch struct { + Trigger map[string]map[string]interface{} `json:"trigger"` + Input map[string]map[string]interface{} `json:"input"` + Condition map[string]map[string]interface{} `json:"condition"` + Transform map[string]interface{} `json:"transform,omitempty"` + ThrottlePeriod string `json:"throttle_period,omitempty"` + ThrottlePeriodInMillis int64 `json:"throttle_period_in_millis,omitempty"` + Actions map[string]*XPackWatchActionStatus `json:"actions"` + Metadata map[string]interface{} `json:"metadata,omitempty"` + Status *XPackWatchStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_put_watch.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_put_watch.go new file mode 100644 index 0000000..0329825 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_put_watch.go @@ -0,0 +1,212 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" + + "github.com/olivere/elastic/v7/uritemplates" +) + +// XPackWatcherPutWatchService either registers a new watch in Watcher +// or update an existing one. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-put-watch.html. +type XPackWatcherPutWatchService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + id string + active *bool + masterTimeout string + ifSeqNo *int64 + ifPrimaryTerm *int64 + body interface{} +} + +// NewXPackWatcherPutWatchService creates a new XPackWatcherPutWatchService. +func NewXPackWatcherPutWatchService(client *Client) *XPackWatcherPutWatchService { + return &XPackWatcherPutWatchService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherPutWatchService) Pretty(pretty bool) *XPackWatcherPutWatchService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherPutWatchService) Human(human bool) *XPackWatcherPutWatchService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherPutWatchService) ErrorTrace(errorTrace bool) *XPackWatcherPutWatchService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherPutWatchService) FilterPath(filterPath ...string) *XPackWatcherPutWatchService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherPutWatchService) Header(name string, value string) *XPackWatcherPutWatchService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherPutWatchService) Headers(headers http.Header) *XPackWatcherPutWatchService { + s.headers = headers + return s +} + +// Id of the watch to upsert. +func (s *XPackWatcherPutWatchService) Id(id string) *XPackWatcherPutWatchService { + s.id = id + return s +} + +// Active specifies whether the watch is in/active by default. +func (s *XPackWatcherPutWatchService) Active(active bool) *XPackWatcherPutWatchService { + s.active = &active + return s +} + +// MasterTimeout is an explicit operation timeout for connection to master node. +func (s *XPackWatcherPutWatchService) MasterTimeout(masterTimeout string) *XPackWatcherPutWatchService { + s.masterTimeout = masterTimeout + return s +} + +// IfSeqNo indicates to update the watch only if the last operation that +// has changed the watch has the specified sequence number. +func (s *XPackWatcherPutWatchService) IfSeqNo(seqNo int64) *XPackWatcherPutWatchService { + s.ifSeqNo = &seqNo + return s +} + +// IfPrimaryTerm indicates to update the watch only if the last operation that +// has changed the watch has the specified primary term. +func (s *XPackWatcherPutWatchService) IfPrimaryTerm(primaryTerm int64) *XPackWatcherPutWatchService { + s.ifPrimaryTerm = &primaryTerm + return s +} + +// Body specifies the watch. Use a string or a type that will get serialized as JSON. +func (s *XPackWatcherPutWatchService) Body(body interface{}) *XPackWatcherPutWatchService { + s.body = body + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherPutWatchService) buildURL() (string, url.Values, error) { + // Build URL + path, err := uritemplates.Expand("/_watcher/watch/{id}", map[string]string{ + "id": s.id, + }) + if err != nil { + return "", url.Values{}, err + } + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.active; v != nil { + params.Set("active", fmt.Sprint(*v)) + } + if s.masterTimeout != "" { + params.Set("master_timeout", s.masterTimeout) + } + if v := s.ifSeqNo; v != nil { + params.Set("if_seq_no", fmt.Sprintf("%d", *v)) + } + if v := s.ifPrimaryTerm; v != nil { + params.Set("if_primary_term", fmt.Sprintf("%d", *v)) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherPutWatchService) Validate() error { + var invalid []string + if s.id == "" { + invalid = append(invalid, "Id") + } + if s.body == nil { + invalid = append(invalid, "Body") + } + if len(invalid) > 0 { + return fmt.Errorf("missing required fields: %v", invalid) + } + return nil +} + +// Do executes the operation. +func (s *XPackWatcherPutWatchService) Do(ctx context.Context) (*XPackWatcherPutWatchResponse, 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, PerformRequestOptions{ + Method: "PUT", + Path: path, + Params: params, + Body: s.body, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherPutWatchResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherPutWatchResponse is the response of XPackWatcherPutWatchService.Do. +type XPackWatcherPutWatchResponse struct { +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_start.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_start.go new file mode 100644 index 0000000..3fb29a7 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_start.go @@ -0,0 +1,137 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" +) + +// XPackWatcherStartService starts the watcher service if it is not already running. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-start.html. +type XPackWatcherStartService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers +} + +// NewXPackWatcherStartService creates a new XPackWatcherStartService. +func NewXPackWatcherStartService(client *Client) *XPackWatcherStartService { + return &XPackWatcherStartService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherStartService) Pretty(pretty bool) *XPackWatcherStartService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherStartService) Human(human bool) *XPackWatcherStartService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherStartService) ErrorTrace(errorTrace bool) *XPackWatcherStartService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherStartService) FilterPath(filterPath ...string) *XPackWatcherStartService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherStartService) Header(name string, value string) *XPackWatcherStartService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherStartService) Headers(headers http.Header) *XPackWatcherStartService { + s.headers = headers + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherStartService) buildURL() (string, url.Values, error) { + // Build URL path + path := "/_watcher/_start" + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherStartService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackWatcherStartService) Do(ctx context.Context) (*XPackWatcherStartResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherStartResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherStartResponse is the response of XPackWatcherStartService.Do. +type XPackWatcherStartResponse struct { + Acknowledged bool `json:"acknowledged"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_stats.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_stats.go new file mode 100644 index 0000000..9c615c2 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_stats.go @@ -0,0 +1,165 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" +) + +// XPackWatcherStatsService returns the current watcher metrics. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-stats.html. +type XPackWatcherStatsService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers + + metric string + emitStacktraces *bool +} + +// NewXPackWatcherStatsService creates a new XPackWatcherStatsService. +func NewXPackWatcherStatsService(client *Client) *XPackWatcherStatsService { + return &XPackWatcherStatsService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherStatsService) Pretty(pretty bool) *XPackWatcherStatsService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherStatsService) Human(human bool) *XPackWatcherStatsService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherStatsService) ErrorTrace(errorTrace bool) *XPackWatcherStatsService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherStatsService) FilterPath(filterPath ...string) *XPackWatcherStatsService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherStatsService) Header(name string, value string) *XPackWatcherStatsService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherStatsService) Headers(headers http.Header) *XPackWatcherStatsService { + s.headers = headers + return s +} + +// Metric controls what additional stat metrics should be include in the response. +func (s *XPackWatcherStatsService) Metric(metric string) *XPackWatcherStatsService { + s.metric = metric + return s +} + +// EmitStacktraces, if enabled, emits stack traces of currently running watches. +func (s *XPackWatcherStatsService) EmitStacktraces(emitStacktraces bool) *XPackWatcherStatsService { + s.emitStacktraces = &emitStacktraces + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherStatsService) buildURL() (string, url.Values, error) { + // Build URL + path := "/_watcher/stats" + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + if v := s.emitStacktraces; v != nil { + params.Set("emit_stacktraces", fmt.Sprint(*v)) + } + if s.metric != "" { + params.Set("metric", s.metric) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherStatsService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackWatcherStatsService) Do(ctx context.Context) (*XPackWatcherStatsResponse, 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, PerformRequestOptions{ + Method: "GET", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherStatsResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherStatsResponse is the response of XPackWatcherStatsService.Do. +type XPackWatcherStatsResponse struct { + Stats []XPackWatcherStats `json:"stats"` +} + +// XPackWatcherStats represents the stats used in XPackWatcherStatsResponse. +type XPackWatcherStats struct { + WatcherState string `json:"watcher_state"` + WatchCount int `json:"watch_count"` + ExecutionThreadPool map[string]interface{} `json:"execution_thread_pool"` +} diff --git a/vendor/github.com/olivere/elastic/v7/xpack_watcher_stop.go b/vendor/github.com/olivere/elastic/v7/xpack_watcher_stop.go new file mode 100644 index 0000000..d5fe9d0 --- /dev/null +++ b/vendor/github.com/olivere/elastic/v7/xpack_watcher_stop.go @@ -0,0 +1,137 @@ +// Copyright 2012-2018 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/http" + "net/url" + "strings" +) + +// XPackWatcherStopService stops the watcher service if it is running. +// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/watcher-api-stop.html. +type XPackWatcherStopService struct { + client *Client + + pretty *bool // pretty format the returned JSON response + human *bool // return human readable values for statistics + errorTrace *bool // include the stack trace of returned errors + filterPath []string // list of filters used to reduce the response + headers http.Header // custom request-level HTTP headers +} + +// NewXPackWatcherStopService creates a new XPackWatcherStopService. +func NewXPackWatcherStopService(client *Client) *XPackWatcherStopService { + return &XPackWatcherStopService{ + client: client, + } +} + +// Pretty tells Elasticsearch whether to return a formatted JSON response. +func (s *XPackWatcherStopService) Pretty(pretty bool) *XPackWatcherStopService { + s.pretty = &pretty + return s +} + +// Human specifies whether human readable values should be returned in +// the JSON response, e.g. "7.5mb". +func (s *XPackWatcherStopService) Human(human bool) *XPackWatcherStopService { + s.human = &human + return s +} + +// ErrorTrace specifies whether to include the stack trace of returned errors. +func (s *XPackWatcherStopService) ErrorTrace(errorTrace bool) *XPackWatcherStopService { + s.errorTrace = &errorTrace + return s +} + +// FilterPath specifies a list of filters used to reduce the response. +func (s *XPackWatcherStopService) FilterPath(filterPath ...string) *XPackWatcherStopService { + s.filterPath = filterPath + return s +} + +// Header adds a header to the request. +func (s *XPackWatcherStopService) Header(name string, value string) *XPackWatcherStopService { + if s.headers == nil { + s.headers = http.Header{} + } + s.headers.Add(name, value) + return s +} + +// Headers specifies the headers of the request. +func (s *XPackWatcherStopService) Headers(headers http.Header) *XPackWatcherStopService { + s.headers = headers + return s +} + +// buildURL builds the URL for the operation. +func (s *XPackWatcherStopService) buildURL() (string, url.Values, error) { + // Build URL path + path := "/_watcher/_stop" + + // Add query string parameters + params := url.Values{} + if v := s.pretty; v != nil { + params.Set("pretty", fmt.Sprint(*v)) + } + if v := s.human; v != nil { + params.Set("human", fmt.Sprint(*v)) + } + if v := s.errorTrace; v != nil { + params.Set("error_trace", fmt.Sprint(*v)) + } + if len(s.filterPath) > 0 { + params.Set("filter_path", strings.Join(s.filterPath, ",")) + } + return path, params, nil +} + +// Validate checks if the operation is valid. +func (s *XPackWatcherStopService) Validate() error { + return nil +} + +// Do executes the operation. +func (s *XPackWatcherStopService) Do(ctx context.Context) (*XPackWatcherStopResponse, 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, PerformRequestOptions{ + Method: "POST", + Path: path, + Params: params, + Headers: s.headers, + }) + if err != nil { + return nil, err + } + + // Return operation response + ret := new(XPackWatcherStopResponse) + if err := json.Unmarshal(res.Body, ret); err != nil { + return nil, err + } + return ret, nil +} + +// XPackWatcherStopResponse is the response of XPackWatcherStopService.Do. +type XPackWatcherStopResponse struct { + Acknowledged bool `json:"acknowledged"` +} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore new file mode 100644 index 0000000..daf913b --- /dev/null +++ b/vendor/github.com/pkg/errors/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml new file mode 100644 index 0000000..9159de0 --- /dev/null +++ b/vendor/github.com/pkg/errors/.travis.yml @@ -0,0 +1,10 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.11.x + - 1.12.x + - 1.13.x + - tip + +script: + - make check diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile new file mode 100644 index 0000000..ce9d7cd --- /dev/null +++ b/vendor/github.com/pkg/errors/Makefile @@ -0,0 +1,44 @@ +PKGS := github.com/pkg/errors +SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) +GO := go + +check: test vet gofmt misspell unconvert staticcheck ineffassign unparam + +test: + $(GO) test $(PKGS) + +vet: | test + $(GO) vet $(PKGS) + +staticcheck: + $(GO) get honnef.co/go/tools/cmd/staticcheck + staticcheck -checks all $(PKGS) + +misspell: + $(GO) get github.com/client9/misspell/cmd/misspell + misspell \ + -locale GB \ + -error \ + *.md *.go + +unconvert: + $(GO) get github.com/mdempsky/unconvert + unconvert -v $(PKGS) + +ineffassign: + $(GO) get github.com/gordonklaus/ineffassign + find $(SRCDIRS) -name '*.go' | xargs ineffassign + +pedantic: check errcheck + +unparam: + $(GO) get mvdan.cc/unparam + unparam ./... + +errcheck: + $(GO) get github.com/kisielk/errcheck + errcheck $(PKGS) + +gofmt: + @echo Checking code is gofmted + @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md index 6483ba2..54dfdcb 100644 --- a/vendor/github.com/pkg/errors/README.md +++ b/vendor/github.com/pkg/errors/README.md @@ -41,11 +41,18 @@ default: [Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). +## Roadmap + +With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: + +- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) +- 1.0. Final release. + ## Contributing -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. +Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. -Before proposing a change, please discuss your change by raising an issue. +Before sending a PR, please discuss your change by raising an issue. ## License diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go index 842ee80..161aea2 100644 --- a/vendor/github.com/pkg/errors/errors.go +++ b/vendor/github.com/pkg/errors/errors.go @@ -6,7 +6,7 @@ // return err // } // -// which applied recursively up the call stack results in error reports +// which when applied recursively up the call stack results in error reports // without context or debugging information. The errors package allows // programmers to add context to the failure path in their code in a way // that does not destroy the original value of the error. @@ -15,16 +15,17 @@ // // The errors.Wrap function returns a new error that adds context to the // original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example +// together with the supplied message. For example // // _, err := ioutil.ReadAll(r) // if err != nil { // return errors.Wrap(err, "read failed") // } // -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. +// If additional control is required, the errors.WithStack and +// errors.WithMessage functions destructure errors.Wrap into its component +// operations: annotating an error with a stack trace and with a message, +// respectively. // // Retrieving the cause of an error // @@ -38,7 +39,7 @@ // } // // can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be +// the topmost error that does not implement causer, which is assumed to be // the original cause. For example: // // switch err := errors.Cause(err).(type) { @@ -48,16 +49,16 @@ // // unknown error // } // -// causer interface is not exported by this package, but is considered a part -// of stable public API. +// Although the causer interface is not exported by this package, it is +// considered a part of its stable public interface. // // Formatted printing of errors // // All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported +// be formatted by the fmt package. The following verbs are supported: // // %s print the error. If the error has a Cause it will be -// printed recursively +// printed recursively. // %v see %s // %+v extended format. Each Frame of the error's StackTrace will // be printed in detail. @@ -65,13 +66,13 @@ // Retrieving the stack trace of an error or wrapper // // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. +// invoked. This information can be retrieved with the following interface: // // type stackTracer interface { // StackTrace() errors.StackTrace // } // -// Where errors.StackTrace is defined as +// The returned errors.StackTrace type is defined as // // type StackTrace []Frame // @@ -81,12 +82,12 @@ // // if err, ok := err.(stackTracer); ok { // for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) +// fmt.Printf("%+s:%d\n", f, f) // } // } // -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. +// Although the stackTracer interface is not exported by this package, it is +// considered a part of its stable public interface. // // See the documentation for Frame.Format for more details. package errors @@ -158,6 +159,9 @@ type withStack struct { func (w *withStack) Cause() error { return w.error } +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withStack) Unwrap() error { return w.error } + func (w *withStack) Format(s fmt.State, verb rune) { switch verb { case 'v': @@ -192,7 +196,7 @@ func Wrap(err error, message string) error { } // Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. +// at the point Wrapf is called, and the format specifier. // If err is nil, Wrapf returns nil. func Wrapf(err error, format string, args ...interface{}) error { if err == nil { @@ -220,6 +224,18 @@ func WithMessage(err error, message string) error { } } +// WithMessagef annotates err with the format specifier. +// If err is nil, WithMessagef returns nil. +func WithMessagef(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } +} + type withMessage struct { cause error msg string @@ -228,6 +244,9 @@ type withMessage struct { func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } func (w *withMessage) Cause() error { return w.cause } +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withMessage) Unwrap() error { return w.cause } + func (w *withMessage) Format(s fmt.State, verb rune) { switch verb { case 'v': diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go new file mode 100644 index 0000000..be0d10d --- /dev/null +++ b/vendor/github.com/pkg/errors/go113.go @@ -0,0 +1,38 @@ +// +build go1.13 + +package errors + +import ( + stderrors "errors" +) + +// Is reports whether any error in err's chain matches target. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +func Is(err, target error) bool { return stderrors.Is(err, target) } + +// As finds the first error in err's chain that matches target, and if so, sets +// target to that error value and returns true. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error matches target if the error's concrete value is assignable to the value +// pointed to by target, or if the error has a method As(interface{}) bool such that +// As(target) returns true. In the latter case, the As method is responsible for +// setting target. +// +// As will panic if target is not a non-nil pointer to either a type that implements +// error, or to any interface type. As returns false if err is nil. +func As(err error, target interface{}) bool { return stderrors.As(err, target) } + +// Unwrap returns the result of calling the Unwrap method on err, if err's +// type contains an Unwrap method returning error. +// Otherwise, Unwrap returns nil. +func Unwrap(err error) error { + return stderrors.Unwrap(err) +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go index 2874a04..779a834 100644 --- a/vendor/github.com/pkg/errors/stack.go +++ b/vendor/github.com/pkg/errors/stack.go @@ -5,10 +5,13 @@ import ( "io" "path" "runtime" + "strconv" "strings" ) // Frame represents a program counter inside a stack frame. +// For historical reasons if Frame is interpreted as a uintptr +// its value represents the program counter + 1. type Frame uintptr // pc returns the program counter for this frame; @@ -37,6 +40,15 @@ func (f Frame) line() int { return line } +// name returns the name of this function, if known. +func (f Frame) name() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + return fn.Name() +} + // Format formats the frame according to the fmt.Formatter interface. // // %s source file @@ -54,22 +66,16 @@ func (f Frame) Format(s fmt.State, verb rune) { case 's': switch { case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } + io.WriteString(s, f.name()) + io.WriteString(s, "\n\t") + io.WriteString(s, f.file()) default: io.WriteString(s, path.Base(f.file())) } case 'd': - fmt.Fprintf(s, "%d", f.line()) + io.WriteString(s, strconv.Itoa(f.line())) case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) + io.WriteString(s, funcname(f.name())) case 'v': f.Format(s, 's') io.WriteString(s, ":") @@ -77,6 +83,16 @@ func (f Frame) Format(s fmt.State, verb rune) { } } +// MarshalText formats a stacktrace Frame as a text string. The output is the +// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. +func (f Frame) MarshalText() ([]byte, error) { + name := f.name() + if name == "unknown" { + return []byte(name), nil + } + return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil +} + // StackTrace is stack of Frames from innermost (newest) to outermost (oldest). type StackTrace []Frame @@ -94,16 +110,30 @@ func (st StackTrace) Format(s fmt.State, verb rune) { switch { case s.Flag('+'): for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) + io.WriteString(s, "\n") + f.Format(s, verb) } case s.Flag('#'): fmt.Fprintf(s, "%#v", []Frame(st)) default: - fmt.Fprintf(s, "%v", []Frame(st)) + st.formatSlice(s, verb) } case 's': - fmt.Fprintf(s, "%s", []Frame(st)) + st.formatSlice(s, verb) + } +} + +// formatSlice will format this StackTrace into the given buffer as a slice of +// Frame, only valid when called with '%s' or '%v'. +func (st StackTrace) formatSlice(s fmt.State, verb rune) { + io.WriteString(s, "[") + for i, f := range st { + if i > 0 { + io.WriteString(s, " ") + } + f.Format(s, verb) } + io.WriteString(s, "]") } // stack represents a stack of program counters. diff --git a/vendor/gopkg.in/olivere/elastic.v6/LICENSE b/vendor/gopkg.in/olivere/elastic.v6/LICENSE deleted file mode 100644 index 8b22cdb..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) -Copyright © 2012-2015 Oliver Eilhard - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the “Software”), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/vendor/gopkg.in/olivere/elastic.v6/go.mod b/vendor/gopkg.in/olivere/elastic.v6/go.mod deleted file mode 100644 index cde57f5..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/go.mod +++ /dev/null @@ -1,13 +0,0 @@ -module github.com/olivere/elastic/v6 - -require ( - github.com/fortytw2/leaktest v1.2.0 - github.com/google/uuid v0.0.0-20171129191014-dec09d789f3d - github.com/mailru/easyjson v0.0.0-20180730094502-03f2033d19d5 - github.com/olivere/elastic v6.1.25+incompatible - github.com/olivere/env v1.0.0 - github.com/pkg/errors v0.8.0 - github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9 - golang.org/x/net v0.0.0-20180801234040-f4c29de78a2a - golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f -) diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_create.go b/vendor/gopkg.in/olivere/elastic.v6/indices_create.go deleted file mode 100644 index 08d8e53..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_create.go +++ /dev/null @@ -1,136 +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/url" - - "github.com/olivere/elastic/uritemplates" -) - -// IndicesCreateService creates a new index. -// -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-create-index.html -// for details. -type IndicesCreateService struct { - client *Client - pretty bool - index string - timeout string - masterTimeout string - bodyJson interface{} - bodyString string -} - -// NewIndicesCreateService returns a new IndicesCreateService. -func NewIndicesCreateService(client *Client) *IndicesCreateService { - return &IndicesCreateService{client: client} -} - -// Index is the name of the index to create. -func (b *IndicesCreateService) Index(index string) *IndicesCreateService { - b.index = index - return b -} - -// Timeout the explicit operation timeout, e.g. "5s". -func (s *IndicesCreateService) Timeout(timeout string) *IndicesCreateService { - s.timeout = timeout - return s -} - -// MasterTimeout specifies the timeout for connection to master. -func (s *IndicesCreateService) MasterTimeout(masterTimeout string) *IndicesCreateService { - s.masterTimeout = masterTimeout - return s -} - -// Body specifies the configuration of the index as a string. -// It is an alias for BodyString. -func (b *IndicesCreateService) Body(body string) *IndicesCreateService { - b.bodyString = body - return b -} - -// BodyString specifies the configuration of the index as a string. -func (b *IndicesCreateService) BodyString(body string) *IndicesCreateService { - b.bodyString = body - return b -} - -// BodyJson specifies the configuration of the index. The interface{} will -// be serializes as a JSON document, so use a map[string]interface{}. -func (b *IndicesCreateService) BodyJson(body interface{}) *IndicesCreateService { - b.bodyJson = body - return b -} - -// Pretty indicates that the JSON response be indented and human readable. -func (b *IndicesCreateService) Pretty(pretty bool) *IndicesCreateService { - b.pretty = pretty - return b -} - -// Do executes the operation. -func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, error) { - if b.index == "" { - return nil, errors.New("missing index name") - } - - // Build url - path, err := uritemplates.Expand("/{index}", map[string]string{ - "index": b.index, - }) - if err != nil { - return nil, err - } - - params := make(url.Values) - if b.pretty { - params.Set("pretty", "true") - } - if b.masterTimeout != "" { - params.Set("master_timeout", b.masterTimeout) - } - if b.timeout != "" { - params.Set("timeout", b.timeout) - } - - // Setup HTTP request body - var body interface{} - if b.bodyJson != nil { - body = b.bodyJson - } else { - body = b.bodyString - } - - // Get response - res, err := b.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "PUT", - Path: path, - Params: params, - Body: body, - }) - if err != nil { - return nil, err - } - - ret := new(IndicesCreateResult) - if err := b.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -// -- Result of a create index request. - -// 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"` -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_exists_type.go b/vendor/gopkg.in/olivere/elastic.v6/indices_exists_type.go deleted file mode 100644 index 76db6b3..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_exists_type.go +++ /dev/null @@ -1,165 +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" - "net/http" - "net/url" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// IndicesExistsTypeService checks if one or more types exist in one or more indices. -// -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-types-exists.html -// for details. -type IndicesExistsTypeService struct { - client *Client - pretty bool - typ []string - index []string - expandWildcards string - local *bool - ignoreUnavailable *bool - allowNoIndices *bool -} - -// NewIndicesExistsTypeService creates a new IndicesExistsTypeService. -func NewIndicesExistsTypeService(client *Client) *IndicesExistsTypeService { - return &IndicesExistsTypeService{ - client: client, - } -} - -// Index is a list of index names; use `_all` to check the types across all indices. -func (s *IndicesExistsTypeService) Index(indices ...string) *IndicesExistsTypeService { - s.index = append(s.index, indices...) - return s -} - -// Type is a list of document types to check. -func (s *IndicesExistsTypeService) Type(types ...string) *IndicesExistsTypeService { - s.typ = append(s.typ, types...) - return s -} - -// IgnoreUnavailable indicates whether specified concrete indices should be -// ignored when unavailable (missing or closed). -func (s *IndicesExistsTypeService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesExistsTypeService { - 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 *IndicesExistsTypeService) AllowNoIndices(allowNoIndices bool) *IndicesExistsTypeService { - s.allowNoIndices = &allowNoIndices - return s -} - -// ExpandWildcards indicates whether to expand wildcard expression to -// concrete indices that are open, closed or both. -func (s *IndicesExistsTypeService) ExpandWildcards(expandWildcards string) *IndicesExistsTypeService { - s.expandWildcards = expandWildcards - return s -} - -// Local specifies whether to return local information, i.e. do not retrieve -// the state from master node (default: false). -func (s *IndicesExistsTypeService) Local(local bool) *IndicesExistsTypeService { - s.local = &local - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesExistsTypeService) Pretty(pretty bool) *IndicesExistsTypeService { - s.pretty = pretty - return s -} - -// buildURL builds the URL for the operation. -func (s *IndicesExistsTypeService) buildURL() (string, url.Values, error) { - // Build URL - path, err := uritemplates.Expand("/{index}/_mapping/{type}", map[string]string{ - "index": strings.Join(s.index, ","), - "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.ignoreUnavailable != nil { - params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable)) - } - 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.local != nil { - params.Set("local", fmt.Sprintf("%v", *s.local)) - } - return path, params, nil -} - -// Validate checks if the operation is valid. -func (s *IndicesExistsTypeService) Validate() error { - var invalid []string - if len(s.index) == 0 { - invalid = append(invalid, "Index") - } - if len(s.typ) == 0 { - invalid = append(invalid, "Type") - } - if len(invalid) > 0 { - return fmt.Errorf("missing required fields: %v", invalid) - } - return nil -} - -// Do executes the operation. -func (s *IndicesExistsTypeService) Do(ctx context.Context) (bool, error) { - // Check pre-conditions - if err := s.Validate(); err != nil { - return false, err - } - - // Get URL for request - path, params, err := s.buildURL() - if err != nil { - return false, err - } - - // Get HTTP response - res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "HEAD", - Path: path, - Params: params, - IgnoreErrors: []int{404}, - }) - if err != nil { - return false, err - } - - // Return operation response - switch res.StatusCode { - case http.StatusOK: - return true, nil - case http.StatusNotFound: - return false, nil - default: - return false, fmt.Errorf("elastic: got HTTP code %d when it should have been either 200 or 404", res.StatusCode) - } -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_refresh.go b/vendor/gopkg.in/olivere/elastic.v6/indices_refresh.go deleted file mode 100644 index 712cdc5..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_refresh.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" - "fmt" - "net/url" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// RefreshService explicitly refreshes one or more indices. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-refresh.html. -type RefreshService struct { - client *Client - index []string - pretty bool -} - -// NewRefreshService creates a new instance of RefreshService. -func NewRefreshService(client *Client) *RefreshService { - builder := &RefreshService{ - client: client, - } - return builder -} - -// Index specifies the indices to refresh. -func (s *RefreshService) Index(index ...string) *RefreshService { - s.index = append(s.index, index...) - return s -} - -// Pretty asks Elasticsearch to return indented JSON. -func (s *RefreshService) Pretty(pretty bool) *RefreshService { - s.pretty = pretty - return s -} - -// buildURL builds the URL for the operation. -func (s *RefreshService) buildURL() (string, url.Values, error) { - var err error - var path string - - if len(s.index) > 0 { - path, err = uritemplates.Expand("/{index}/_refresh", map[string]string{ - "index": strings.Join(s.index, ","), - }) - } else { - path = "/_refresh" - } - 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)) - } - return path, params, nil -} - -// Do executes the request. -func (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) { - path, params, err := s.buildURL() - if err != nil { - return nil, err - } - - // Get response - res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - }) - if err != nil { - return nil, err - } - - // Return result - ret := new(RefreshResult) - if err := s.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -// -- Result of a refresh request. - -// RefreshResult is the outcome of RefreshService.Do. -type RefreshResult struct { - Shards shardsInfo `json:"_shards,omitempty"` -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/indices_stats.go b/vendor/gopkg.in/olivere/elastic.v6/indices_stats.go deleted file mode 100644 index e237e45..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/indices_stats.go +++ /dev/null @@ -1,392 +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" - "net/url" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// IndicesStatsService provides stats on various metrics of one or more -// indices. See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-stats.html. -type IndicesStatsService struct { - client *Client - pretty bool - metric []string - index []string - level string - types []string - completionFields []string - fielddataFields []string - fields []string - groups []string - human *bool -} - -// NewIndicesStatsService creates a new IndicesStatsService. -func NewIndicesStatsService(client *Client) *IndicesStatsService { - return &IndicesStatsService{ - client: client, - index: make([]string, 0), - metric: make([]string, 0), - completionFields: make([]string, 0), - fielddataFields: make([]string, 0), - fields: make([]string, 0), - groups: make([]string, 0), - types: make([]string, 0), - } -} - -// Metric limits the information returned the specific metrics. Options are: -// docs, store, indexing, get, search, completion, fielddata, flush, merge, -// query_cache, refresh, suggest, and warmer. -func (s *IndicesStatsService) Metric(metric ...string) *IndicesStatsService { - s.metric = append(s.metric, metric...) - return s -} - -// Index is the list of index names; use `_all` or empty string to perform -// the operation on all indices. -func (s *IndicesStatsService) Index(indices ...string) *IndicesStatsService { - s.index = append(s.index, indices...) - return s -} - -// Type is a list of document types for the `indexing` index metric. -func (s *IndicesStatsService) Type(types ...string) *IndicesStatsService { - s.types = append(s.types, types...) - return s -} - -// Level returns stats aggregated at cluster, index or shard level. -func (s *IndicesStatsService) Level(level string) *IndicesStatsService { - s.level = level - return s -} - -// CompletionFields is a list of fields for `fielddata` and `suggest` -// index metric (supports wildcards). -func (s *IndicesStatsService) CompletionFields(completionFields ...string) *IndicesStatsService { - s.completionFields = append(s.completionFields, completionFields...) - return s -} - -// FielddataFields is a list of fields for `fielddata` index metric (supports wildcards). -func (s *IndicesStatsService) FielddataFields(fielddataFields ...string) *IndicesStatsService { - s.fielddataFields = append(s.fielddataFields, fielddataFields...) - return s -} - -// Fields is a list of fields for `fielddata` and `completion` index metric -// (supports wildcards). -func (s *IndicesStatsService) Fields(fields ...string) *IndicesStatsService { - s.fields = append(s.fields, fields...) - return s -} - -// Groups is a list of search groups for `search` index metric. -func (s *IndicesStatsService) Groups(groups ...string) *IndicesStatsService { - s.groups = append(s.groups, groups...) - return s -} - -// Human indicates whether to return time and byte values in human-readable format.. -func (s *IndicesStatsService) Human(human bool) *IndicesStatsService { - s.human = &human - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *IndicesStatsService) Pretty(pretty bool) *IndicesStatsService { - s.pretty = pretty - return s -} - -// buildURL builds the URL for the operation. -func (s *IndicesStatsService) buildURL() (string, url.Values, error) { - var err error - var path string - if len(s.index) > 0 && len(s.metric) > 0 { - path, err = uritemplates.Expand("/{index}/_stats/{metric}", map[string]string{ - "index": strings.Join(s.index, ","), - "metric": strings.Join(s.metric, ","), - }) - } else if len(s.index) > 0 { - path, err = uritemplates.Expand("/{index}/_stats", map[string]string{ - "index": strings.Join(s.index, ","), - }) - } else if len(s.metric) > 0 { - path, err = uritemplates.Expand("/_stats/{metric}", map[string]string{ - "metric": strings.Join(s.metric, ","), - }) - } else { - path = "/_stats" - } - if err != nil { - return "", url.Values{}, err - } - - // Add query string parameters - params := url.Values{} - if s.pretty { - params.Set("pretty", "true") - } - if len(s.groups) > 0 { - params.Set("groups", strings.Join(s.groups, ",")) - } - if s.human != nil { - params.Set("human", fmt.Sprintf("%v", *s.human)) - } - if s.level != "" { - params.Set("level", s.level) - } - if len(s.types) > 0 { - params.Set("types", strings.Join(s.types, ",")) - } - if len(s.completionFields) > 0 { - params.Set("completion_fields", strings.Join(s.completionFields, ",")) - } - if len(s.fielddataFields) > 0 { - params.Set("fielddata_fields", strings.Join(s.fielddataFields, ",")) - } - if len(s.fields) > 0 { - params.Set("fields", strings.Join(s.fields, ",")) - } - return path, params, nil -} - -// Validate checks if the operation is valid. -func (s *IndicesStatsService) Validate() error { - return nil -} - -// Do executes the operation. -func (s *IndicesStatsService) Do(ctx context.Context) (*IndicesStatsResponse, 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, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, - }) - if err != nil { - return nil, err - } - - // Return operation response - ret := new(IndicesStatsResponse) - if err := s.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -// IndicesStatsResponse is the response of IndicesStatsService.Do. -type IndicesStatsResponse struct { - // Shards provides information returned from shards. - Shards shardsInfo `json:"_shards"` - - // All provides summary stats about all indices. - All *IndexStats `json:"_all,omitempty"` - - // Indices provides a map into the stats of an index. The key of the - // map is the index name. - Indices map[string]*IndexStats `json:"indices,omitempty"` -} - -// IndexStats is index stats for a specific index. -type IndexStats struct { - Primaries *IndexStatsDetails `json:"primaries,omitempty"` - Total *IndexStatsDetails `json:"total,omitempty"` -} - -type IndexStatsDetails struct { - Docs *IndexStatsDocs `json:"docs,omitempty"` - Store *IndexStatsStore `json:"store,omitempty"` - Indexing *IndexStatsIndexing `json:"indexing,omitempty"` - Get *IndexStatsGet `json:"get,omitempty"` - Search *IndexStatsSearch `json:"search,omitempty"` - Merges *IndexStatsMerges `json:"merges,omitempty"` - Refresh *IndexStatsRefresh `json:"refresh,omitempty"` - Flush *IndexStatsFlush `json:"flush,omitempty"` - Warmer *IndexStatsWarmer `json:"warmer,omitempty"` - FilterCache *IndexStatsFilterCache `json:"filter_cache,omitempty"` - IdCache *IndexStatsIdCache `json:"id_cache,omitempty"` - Fielddata *IndexStatsFielddata `json:"fielddata,omitempty"` - Percolate *IndexStatsPercolate `json:"percolate,omitempty"` - Completion *IndexStatsCompletion `json:"completion,omitempty"` - Segments *IndexStatsSegments `json:"segments,omitempty"` - Translog *IndexStatsTranslog `json:"translog,omitempty"` - Suggest *IndexStatsSuggest `json:"suggest,omitempty"` - QueryCache *IndexStatsQueryCache `json:"query_cache,omitempty"` -} - -type IndexStatsDocs struct { - Count int64 `json:"count,omitempty"` - Deleted int64 `json:"deleted,omitempty"` -} - -type IndexStatsStore struct { - Size string `json:"size,omitempty"` // human size, e.g. 119.3mb - SizeInBytes int64 `json:"size_in_bytes,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"` -} - -type IndexStatsGet struct { - Total int64 `json:"total,omitempty"` - GetTime string `json:"get_time,omitempty"` - TimeInMillis int64 `json:"time_in_millis,omitempty"` - ExistsTotal int64 `json:"exists_total,omitempty"` - ExistsTime string `json:"exists_time,omitempty"` - ExistsTimeInMillis int64 `json:"exists_time_in_millis,omitempty"` - MissingTotal int64 `json:"missing_total,omitempty"` - MissingTime string `json:"missing_time,omitempty"` - MissingTimeInMillis int64 `json:"missing_time_in_millis,omitempty"` - Current int64 `json:"current,omitempty"` -} - -type IndexStatsSearch struct { - OpenContexts int64 `json:"open_contexts,omitempty"` - QueryTotal int64 `json:"query_total,omitempty"` - QueryTime string `json:"query_time,omitempty"` - QueryTimeInMillis int64 `json:"query_time_in_millis,omitempty"` - QueryCurrent int64 `json:"query_current,omitempty"` - FetchTotal int64 `json:"fetch_total,omitempty"` - FetchTime string `json:"fetch_time,omitempty"` - FetchTimeInMillis int64 `json:"fetch_time_in_millis,omitempty"` - FetchCurrent int64 `json:"fetch_current,omitempty"` - ScrollTotal int64 `json:"scroll_total,omitempty"` - ScrollTime string `json:"scroll_time,omitempty"` - ScrollTimeInMillis int64 `json:"scroll_time_in_millis,omitempty"` - ScrollCurrent int64 `json:"scroll_current,omitempty"` - SuggestTotal int64 `json:"suggest_total,omitempty"` - SuggestTime string `json:"suggest_time,omitempty"` - SuggestTimeInMillis int64 `json:"suggest_time_in_millis,omitempty"` - SuggestCurrent int64 `json:"suggest_current,omitempty"` -} - -type IndexStatsMerges struct { - Current int64 `json:"current,omitempty"` - CurrentDocs int64 `json:"current_docs,omitempty"` - CurrentSize string `json:"current_size,omitempty"` - CurrentSizeInBytes int64 `json:"current_size_in_bytes,omitempty"` - Total int64 `json:"total,omitempty"` - TotalTime string `json:"total_time,omitempty"` - TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` - TotalDocs int64 `json:"total_docs,omitempty"` - TotalSize string `json:"total_size,omitempty"` - TotalSizeInBytes int64 `json:"total_size_in_bytes,omitempty"` -} - -type IndexStatsRefresh struct { - Total int64 `json:"total,omitempty"` - TotalTime string `json:"total_time,omitempty"` - TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` -} - -type IndexStatsFlush struct { - Total int64 `json:"total,omitempty"` - TotalTime string `json:"total_time,omitempty"` - TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` -} - -type IndexStatsWarmer struct { - Current int64 `json:"current,omitempty"` - Total int64 `json:"total,omitempty"` - TotalTime string `json:"total_time,omitempty"` - TotalTimeInMillis int64 `json:"total_time_in_millis,omitempty"` -} - -type IndexStatsFilterCache struct { - MemorySize string `json:"memory_size,omitempty"` - MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` - Evictions int64 `json:"evictions,omitempty"` -} - -type IndexStatsIdCache struct { - MemorySize string `json:"memory_size,omitempty"` - MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` -} - -type IndexStatsFielddata struct { - MemorySize string `json:"memory_size,omitempty"` - MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` - Evictions int64 `json:"evictions,omitempty"` -} - -type IndexStatsPercolate struct { - Total int64 `json:"total,omitempty"` - GetTime string `json:"get_time,omitempty"` - TimeInMillis int64 `json:"time_in_millis,omitempty"` - Current int64 `json:"current,omitempty"` - MemorySize string `json:"memory_size,omitempty"` - MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` - Queries int64 `json:"queries,omitempty"` -} - -type IndexStatsCompletion struct { - Size string `json:"size,omitempty"` - SizeInBytes int64 `json:"size_in_bytes,omitempty"` -} - -type IndexStatsSegments struct { - Count int64 `json:"count,omitempty"` - Memory string `json:"memory,omitempty"` - MemoryInBytes int64 `json:"memory_in_bytes,omitempty"` - IndexWriterMemory string `json:"index_writer_memory,omitempty"` - IndexWriterMemoryInBytes int64 `json:"index_writer_memory_in_bytes,omitempty"` - IndexWriterMaxMemory string `json:"index_writer_max_memory,omitempty"` - IndexWriterMaxMemoryInBytes int64 `json:"index_writer_max_memory_in_bytes,omitempty"` - VersionMapMemory string `json:"version_map_memory,omitempty"` - VersionMapMemoryInBytes int64 `json:"version_map_memory_in_bytes,omitempty"` - FixedBitSetMemory string `json:"fixed_bit_set,omitempty"` - FixedBitSetMemoryInBytes int64 `json:"fixed_bit_set_memory_in_bytes,omitempty"` -} - -type IndexStatsTranslog struct { - Operations int64 `json:"operations,omitempty"` - Size string `json:"size,omitempty"` - SizeInBytes int64 `json:"size_in_bytes,omitempty"` -} - -type IndexStatsSuggest struct { - Total int64 `json:"total,omitempty"` - Time string `json:"time,omitempty"` - TimeInMillis int64 `json:"time_in_millis,omitempty"` - Current int64 `json:"current,omitempty"` -} - -type IndexStatsQueryCache struct { - MemorySize string `json:"memory_size,omitempty"` - MemorySizeInBytes int64 `json:"memory_size_in_bytes,omitempty"` - Evictions int64 `json:"evictions,omitempty"` - HitCount int64 `json:"hit_count,omitempty"` - MissCount int64 `json:"miss_count,omitempty"` -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/ping.go b/vendor/gopkg.in/olivere/elastic.v6/ping.go deleted file mode 100644 index 5c2d34f..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/ping.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" - "encoding/json" - "net/http" - "net/url" -) - -// PingService checks if an Elasticsearch server on a given URL is alive. -// When asked for, it can also return various information about the -// Elasticsearch server, e.g. the Elasticsearch version number. -// -// Ping simply starts a HTTP GET request to the URL of the server. -// If the server responds with HTTP Status code 200 OK, the server is alive. -type PingService struct { - client *Client - url string - timeout string - httpHeadOnly bool - pretty bool -} - -// PingResult is the result returned from querying the Elasticsearch server. -type PingResult struct { - Name string `json:"name"` - ClusterName string `json:"cluster_name"` - Version struct { - Number string `json:"number"` - BuildHash string `json:"build_hash"` - BuildTimestamp string `json:"build_timestamp"` - BuildSnapshot bool `json:"build_snapshot"` - LuceneVersion string `json:"lucene_version"` - } `json:"version"` - TagLine string `json:"tagline"` -} - -func NewPingService(client *Client) *PingService { - return &PingService{ - client: client, - url: DefaultURL, - httpHeadOnly: false, - pretty: false, - } -} - -func (s *PingService) URL(url string) *PingService { - s.url = url - return s -} - -func (s *PingService) Timeout(timeout string) *PingService { - s.timeout = timeout - return s -} - -// HeadOnly makes the service to only return the status code in Do; -// the PingResult will be nil. -func (s *PingService) HttpHeadOnly(httpHeadOnly bool) *PingService { - s.httpHeadOnly = httpHeadOnly - return s -} - -func (s *PingService) Pretty(pretty bool) *PingService { - s.pretty = pretty - return s -} - -// Do returns the PingResult, the HTTP status code of the Elasticsearch -// server, and an error. -func (s *PingService) Do(ctx context.Context) (*PingResult, int, error) { - s.client.mu.RLock() - basicAuth := s.client.basicAuth - basicAuthUsername := s.client.basicAuthUsername - basicAuthPassword := s.client.basicAuthPassword - s.client.mu.RUnlock() - - url_ := s.url + "/" - - params := make(url.Values) - if s.timeout != "" { - params.Set("timeout", s.timeout) - } - if s.pretty { - params.Set("pretty", "true") - } - if len(params) > 0 { - url_ += "?" + params.Encode() - } - - var method string - if s.httpHeadOnly { - method = "HEAD" - } else { - method = "GET" - } - - // Notice: This service must NOT use PerformRequest! - req, err := NewRequest(method, url_) - if err != nil { - return nil, 0, err - } - - if basicAuth { - req.SetBasicAuth(basicAuthUsername, basicAuthPassword) - } - - res, err := s.client.c.Do((*http.Request)(req).WithContext(ctx)) - if err != nil { - return nil, 0, err - } - defer res.Body.Close() - - var ret *PingResult - if !s.httpHeadOnly { - ret = new(PingResult) - if err := json.NewDecoder(res.Body).Decode(ret); err != nil { - return nil, res.StatusCode, err - } - } - - return ret, res.StatusCode, nil -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/search.go b/vendor/gopkg.in/olivere/elastic.v6/search.go deleted file mode 100644 index 58e962a..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/search.go +++ /dev/null @@ -1,595 +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" - "net/url" - "reflect" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// Search for documents in Elasticsearch. -type SearchService struct { - client *Client - searchSource *SearchSource - source interface{} - pretty bool - filterPath []string - searchType string - index []string - typ []string - routing string - preference string - requestCache *bool - ignoreUnavailable *bool - allowNoIndices *bool - expandWildcards string -} - -// NewSearchService creates a new service for searching in Elasticsearch. -func NewSearchService(client *Client) *SearchService { - builder := &SearchService{ - client: client, - searchSource: NewSearchSource(), - } - return builder -} - -// SearchSource sets the search source builder to use with this service. -func (s *SearchService) SearchSource(searchSource *SearchSource) *SearchService { - s.searchSource = searchSource - if s.searchSource == nil { - s.searchSource = NewSearchSource() - } - return s -} - -// Source allows the user to set the request body manually without using -// any of the structs and interfaces in Elastic. -func (s *SearchService) Source(source interface{}) *SearchService { - s.source = source - return s -} - -// FilterPath allows reducing the response, a mechanism known as -// response filtering and described here: -// https://www.elastic.co/guide/en/elasticsearch/reference/6.2/common-options.html#common-options-response-filtering. -func (s *SearchService) FilterPath(filterPath ...string) *SearchService { - s.filterPath = append(s.filterPath, filterPath...) - return s -} - -// Index sets the names of the indices to use for search. -func (s *SearchService) Index(index ...string) *SearchService { - s.index = append(s.index, index...) - return s -} - -// Types adds search restrictions for a list of types. -func (s *SearchService) Type(typ ...string) *SearchService { - s.typ = append(s.typ, typ...) - return s -} - -// Pretty enables the caller to indent the JSON output. -func (s *SearchService) Pretty(pretty bool) *SearchService { - s.pretty = pretty - return s -} - -// Timeout sets the timeout to use, e.g. "1s" or "1000ms". -func (s *SearchService) Timeout(timeout string) *SearchService { - s.searchSource = s.searchSource.Timeout(timeout) - return s -} - -// Profile sets the Profile API flag on the search source. -// When enabled, a search executed by this service will return query -// profiling data. -func (s *SearchService) Profile(profile bool) *SearchService { - s.searchSource = s.searchSource.Profile(profile) - return s -} - -// Collapse adds field collapsing. -func (s *SearchService) Collapse(collapse *CollapseBuilder) *SearchService { - s.searchSource = s.searchSource.Collapse(collapse) - return s -} - -// TimeoutInMillis sets the timeout in milliseconds. -func (s *SearchService) TimeoutInMillis(timeoutInMillis int) *SearchService { - s.searchSource = s.searchSource.TimeoutInMillis(timeoutInMillis) - 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: -// "dfs_query_then_fetch" and "query_then_fetch". -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-search-type.html -// for details. -func (s *SearchService) SearchType(searchType string) *SearchService { - s.searchType = searchType - return s -} - -// Routing is a list of specific routing values to control the shards -// the search will be executed on. -func (s *SearchService) Routing(routings ...string) *SearchService { - s.routing = strings.Join(routings, ",") - return s -} - -// Preference sets the preference to execute the search. Defaults to -// randomize across shards ("random"). Can be set to "_local" to prefer -// local shards, "_primary" to execute on primary shards only, -// or a custom value which guarantees that the same order will be used -// across different requests. -func (s *SearchService) Preference(preference string) *SearchService { - s.preference = preference - return s -} - -// RequestCache indicates whether the cache should be used for this -// request or not, defaults to index level setting. -func (s *SearchService) RequestCache(requestCache bool) *SearchService { - s.requestCache = &requestCache - return s -} - -// Query sets the query to perform, e.g. MatchAllQuery. -func (s *SearchService) Query(query Query) *SearchService { - s.searchSource = s.searchSource.Query(query) - return s -} - -// PostFilter will be executed after the query has been executed and -// only affects the search hits, not the aggregations. -// This filter is always executed as the last filtering mechanism. -func (s *SearchService) PostFilter(postFilter Query) *SearchService { - s.searchSource = s.searchSource.PostFilter(postFilter) - return s -} - -// FetchSource indicates whether the response should contain the stored -// _source for every hit. -func (s *SearchService) FetchSource(fetchSource bool) *SearchService { - s.searchSource = s.searchSource.FetchSource(fetchSource) - return s -} - -// FetchSourceContext indicates how the _source should be fetched. -func (s *SearchService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *SearchService { - s.searchSource = s.searchSource.FetchSourceContext(fetchSourceContext) - return s -} - -// Highlight adds highlighting to the search. -func (s *SearchService) Highlight(highlight *Highlight) *SearchService { - s.searchSource = s.searchSource.Highlight(highlight) - return s -} - -// GlobalSuggestText defines the global text to use with all suggesters. -// This avoids repetition. -func (s *SearchService) GlobalSuggestText(globalText string) *SearchService { - s.searchSource = s.searchSource.GlobalSuggestText(globalText) - return s -} - -// Suggester adds a suggester to the search. -func (s *SearchService) Suggester(suggester Suggester) *SearchService { - s.searchSource = s.searchSource.Suggester(suggester) - return s -} - -// Aggregation adds an aggreation to perform as part of the search. -func (s *SearchService) Aggregation(name string, aggregation Aggregation) *SearchService { - s.searchSource = s.searchSource.Aggregation(name, aggregation) - return s -} - -// MinScore sets the minimum score below which docs will be filtered out. -func (s *SearchService) MinScore(minScore float64) *SearchService { - s.searchSource = s.searchSource.MinScore(minScore) - return s -} - -// From index to start the search from. Defaults to 0. -func (s *SearchService) From(from int) *SearchService { - s.searchSource = s.searchSource.From(from) - return s -} - -// Size is the number of search hits to return. Defaults to 10. -func (s *SearchService) Size(size int) *SearchService { - s.searchSource = s.searchSource.Size(size) - return s -} - -// Explain indicates whether each search hit should be returned with -// an explanation of the hit (ranking). -func (s *SearchService) Explain(explain bool) *SearchService { - s.searchSource = s.searchSource.Explain(explain) - return s -} - -// Version indicates whether each search hit should be returned with -// a version associated to it. -func (s *SearchService) Version(version bool) *SearchService { - s.searchSource = s.searchSource.Version(version) - return s -} - -// Sort adds a sort order. -func (s *SearchService) Sort(field string, ascending bool) *SearchService { - s.searchSource = s.searchSource.Sort(field, ascending) - return s -} - -// SortWithInfo adds a sort order. -func (s *SearchService) SortWithInfo(info SortInfo) *SearchService { - s.searchSource = s.searchSource.SortWithInfo(info) - return s -} - -// SortBy adds a sort order. -func (s *SearchService) SortBy(sorter ...Sorter) *SearchService { - s.searchSource = s.searchSource.SortBy(sorter...) - return s -} - -// NoStoredFields indicates that no stored fields should be loaded, resulting in only -// id and type to be returned per field. -func (s *SearchService) NoStoredFields() *SearchService { - s.searchSource = s.searchSource.NoStoredFields() - return s -} - -// StoredField adds a single field to load and return (note, must be stored) as -// part of the search request. If none are specified, the source of the -// document will be returned. -func (s *SearchService) StoredField(fieldName string) *SearchService { - s.searchSource = s.searchSource.StoredField(fieldName) - return s -} - -// StoredFields sets the fields to load and return as part of the search request. -// If none are specified, the source of the document will be returned. -func (s *SearchService) StoredFields(fields ...string) *SearchService { - s.searchSource = s.searchSource.StoredFields(fields...) - return s -} - -// TrackScores is applied when sorting and controls if scores will be -// tracked as well. Defaults to false. -func (s *SearchService) TrackScores(trackScores bool) *SearchService { - s.searchSource = s.searchSource.TrackScores(trackScores) - return s -} - -// 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.2/search-request-search-after.html -func (s *SearchService) SearchAfter(sortValues ...interface{}) *SearchService { - s.searchSource = s.searchSource.SearchAfter(sortValues...) - return s -} - -// IgnoreUnavailable indicates whether the specified concrete indices -// should be ignored when unavailable (missing or closed). -func (s *SearchService) IgnoreUnavailable(ignoreUnavailable bool) *SearchService { - 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 *SearchService) AllowNoIndices(allowNoIndices bool) *SearchService { - s.allowNoIndices = &allowNoIndices - return s -} - -// ExpandWildcards indicates whether to expand wildcard expression to -// concrete indices that are open, closed or both. -func (s *SearchService) ExpandWildcards(expandWildcards string) *SearchService { - s.expandWildcards = expandWildcards - return s -} - -// buildURL builds the URL for the operation. -func (s *SearchService) buildURL() (string, url.Values, error) { - var err error - var path string - - if len(s.index) > 0 && len(s.typ) > 0 { - path, err = uritemplates.Expand("/{index}/{type}/_search", map[string]string{ - "index": strings.Join(s.index, ","), - "type": strings.Join(s.typ, ","), - }) - } else if len(s.index) > 0 { - path, err = uritemplates.Expand("/{index}/_search", map[string]string{ - "index": strings.Join(s.index, ","), - }) - } else if len(s.typ) > 0 { - path, err = uritemplates.Expand("/_all/{type}/_search", map[string]string{ - "type": strings.Join(s.typ, ","), - }) - } else { - path = "/_search" - } - 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.searchType != "" { - params.Set("search_type", s.searchType) - } - if s.routing != "" { - params.Set("routing", s.routing) - } - if s.preference != "" { - params.Set("preference", s.preference) - } - if s.requestCache != nil { - params.Set("request_cache", fmt.Sprintf("%v", *s.requestCache)) - } - 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)) - } - if len(s.filterPath) > 0 { - params.Set("filter_path", strings.Join(s.filterPath, ",")) - } - return path, params, nil -} - -// Validate checks if the operation is valid. -func (s *SearchService) Validate() error { - return nil -} - -// Do executes the search and returns a SearchResult. -func (s *SearchService) Do(ctx context.Context) (*SearchResult, 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 - } - - // Perform request - var body interface{} - if s.source != nil { - body = s.source - } else { - src, err := s.searchSource.Source() - if err != nil { - return nil, err - } - body = src - } - res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, - }) - if err != nil { - return nil, err - } - - // Return search results - ret := new(SearchResult) - if err := s.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -// 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 - Hits *SearchHits `json:"hits"` // the actual search hits - Suggest SearchSuggest `json:"suggest"` // results from suggesters - Aggregations Aggregations `json:"aggregations"` // results from aggregations - TimedOut bool `json:"timed_out"` // true if the search timed out - Error *ErrorDetails `json:"error,omitempty"` // only used in MultiGet - Profile *SearchProfile `json:"profile,omitempty"` // profiling results, if optional Profile API was active for this search - Shards *shardsInfo `json:"_shards,omitempty"` // shard information -} - -// TotalHits is a convenience function to return the number of hits for -// a search result. -func (r *SearchResult) TotalHits() int64 { - if r.Hits != nil { - return r.Hits.TotalHits - } - return 0 -} - -// 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 -func (r *SearchResult) Each(typ reflect.Type) []interface{} { - if r.Hits == nil || r.Hits.Hits == nil || len(r.Hits.Hits) == 0 { - return nil - } - var slice []interface{} - for _, hit := range r.Hits.Hits { - v := reflect.New(typ).Elem() - if hit.Source == nil { - slice = append(slice, v.Interface()) - continue - } - if err := json.Unmarshal(*hit.Source, v.Addr().Interface()); err == nil { - slice = append(slice, v.Interface()) - } - } - return slice -} - -// SearchHits specifies the list of search hits. -type SearchHits struct { - TotalHits int64 `json:"total"` // total number of hits found - MaxScore *float64 `json:"max_score"` // maximum score of all hits - Hits []*SearchHit `json:"hits"` // the actual hits returned -} - -// NestedHit is a nested innerhit -type NestedHit struct { - Field string `json:"field"` - Offset int `json:"offset"` -} - -// SearchHit is a single hit. -type SearchHit struct { - Score *float64 `json:"_score"` // computed score - Index string `json:"_index"` // index name - Type string `json:"_type"` // type meta field - Id string `json:"_id"` // external or internal - Uid string `json:"_uid"` // uid meta field (see MapperService.java for all meta fields) - Routing string `json:"_routing"` // routing meta field - Parent string `json:"_parent"` // parent meta field - Version *int64 `json:"_version"` // version number, when Version is set to true in SearchService - Sort []interface{} `json:"sort"` // sort information - Highlight SearchHitHighlight `json:"highlight"` // highlighter information - Source *json.RawMessage `json:"_source"` // stored document source - Fields map[string]interface{} `json:"fields"` // returned (stored) fields - Explanation *SearchExplanation `json:"_explanation"` // explains how the score was computed - MatchedQueries []string `json:"matched_queries"` // matched queries - InnerHits map[string]*SearchHitInnerHits `json:"inner_hits"` // inner hits with ES >= 1.5.0 - Nested *NestedHit `json:"_nested"` - - // Shard - // HighlightFields - // SortValues - // MatchedFilters -} - -type SearchHitInnerHits struct { - Hits *SearchHits `json:"hits"` -} - -// SearchExplanation explains how the score for a hit was computed. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/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:" - Details []SearchExplanation `json:"details,omitempty"` // recursive details -} - -// Suggest - -// SearchSuggest is a map of suggestions. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters.html. -type SearchSuggest map[string][]SearchSuggestion - -// SearchSuggestion is a single search suggestion. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters.html. -type SearchSuggestion struct { - Text string `json:"text"` - Offset int `json:"offset"` - Length int `json:"length"` - Options []SearchSuggestionOption `json:"options"` -} - -// SearchSuggestionOption is an option of a SearchSuggestion. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-suggesters.html. -type SearchSuggestionOption struct { - Text string `json:"text"` - Index string `json:"_index"` - Type string `json:"_type"` - Id string `json:"_id"` - Score float64 `json:"score"` // term and phrase suggesters uses "score" as of 6.2.4 - ScoreUnderscore float64 `json:"_score"` // completion and context suggesters uses "_score" as of 6.2.4 - Highlighted string `json:"highlighted"` - CollateMatch bool `json:"collate_match"` - Freq int `json:"freq"` // from TermSuggestion.Option in Java API - Source *json.RawMessage `json:"_source"` -} - -// SearchProfile is a list of shard profiling data collected during -// query execution in the "profile" section of a SearchResult -type SearchProfile struct { - Shards []SearchProfileShardResult `json:"shards"` -} - -// SearchProfileShardResult returns the profiling data for a single shard -// accessed during the search query or aggregation. -type SearchProfileShardResult struct { - ID string `json:"id"` - Searches []QueryProfileShardResult `json:"searches"` - Aggregations []ProfileResult `json:"aggregations"` -} - -// QueryProfileShardResult is a container class to hold the profile results -// for a single shard in the request. It comtains a list of query profiles, -// a collector tree and a total rewrite tree. -type QueryProfileShardResult struct { - Query []ProfileResult `json:"query,omitempty"` - RewriteTime int64 `json:"rewrite_time,omitempty"` - Collector []interface{} `json:"collector,omitempty"` -} - -// CollectorResult holds the profile timings of the collectors used in the -// search. Children's CollectorResults may be embedded inside of a parent -// CollectorResult. -type CollectorResult struct { - Name string `json:"name,omitempty"` - Reason string `json:"reason,omitempty"` - Time string `json:"time,omitempty"` - TimeNanos int64 `json:"time_in_nanos,omitempty"` - Children []CollectorResult `json:"children,omitempty"` -} - -// ProfileResult is the internal representation of a profiled query, -// corresponding to a single node in the query tree. -type ProfileResult struct { - Type string `json:"type"` - Description string `json:"description,omitempty"` - NodeTime string `json:"time,omitempty"` - NodeTimeNanos int64 `json:"time_in_nanos,omitempty"` - Breakdown map[string]int64 `json:"breakdown,omitempty"` - Children []ProfileResult `json:"children,omitempty"` -} - -// Aggregations (see search_aggs.go) - -// Highlighting - -// SearchHitHighlight is the highlight information of a search hit. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-highlighting.html -// for a general discussion of highlighting. -type SearchHitHighlight map[string][]string diff --git a/vendor/gopkg.in/olivere/elastic.v6/search_request.go b/vendor/gopkg.in/olivere/elastic.v6/search_request.go deleted file mode 100644 index b07dce6..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/search_request.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" - "strings" -) - -// SearchRequest combines a search request and its -// query details (see SearchSource). -// It is used in combination with MultiSearch. -type SearchRequest struct { - searchType string - indices []string - types []string - routing *string - preference *string - requestCache *bool - ignoreUnavailable *bool - allowNoIndices *bool - expandWildcards string - scroll string - source interface{} -} - -// NewSearchRequest creates a new search request. -func NewSearchRequest() *SearchRequest { - return &SearchRequest{} -} - -// SearchRequest must be one of "dfs_query_then_fetch" or -// "query_then_fetch". -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") -} - -// SearchTypeQueryThenFetch sets search type to query_then_fetch. -func (r *SearchRequest) SearchTypeQueryThenFetch() *SearchRequest { - return r.SearchType("query_then_fetch") -} - -func (r *SearchRequest) Index(indices ...string) *SearchRequest { - r.indices = append(r.indices, indices...) - return r -} - -func (r *SearchRequest) HasIndices() bool { - return len(r.indices) > 0 -} - -func (r *SearchRequest) Type(types ...string) *SearchRequest { - r.types = append(r.types, types...) - return r -} - -func (r *SearchRequest) Routing(routing string) *SearchRequest { - r.routing = &routing - return r -} - -func (r *SearchRequest) Routings(routings ...string) *SearchRequest { - if routings != nil { - routings := strings.Join(routings, ",") - r.routing = &routings - } else { - r.routing = nil - } - return r -} - -func (r *SearchRequest) Preference(preference string) *SearchRequest { - r.preference = &preference - return r -} - -func (r *SearchRequest) RequestCache(requestCache bool) *SearchRequest { - r.requestCache = &requestCache - return r -} - -// IgnoreUnavailable indicates whether specified concrete indices should be -// ignored when unavailable (missing or closed). -func (s *SearchRequest) IgnoreUnavailable(ignoreUnavailable bool) *SearchRequest { - 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 *SearchRequest) AllowNoIndices(allowNoIndices bool) *SearchRequest { - s.allowNoIndices = &allowNoIndices - return s -} - -// ExpandWildcards indicates whether to expand wildcard expression to -// concrete indices that are open, closed or both. -func (s *SearchRequest) ExpandWildcards(expandWildcards string) *SearchRequest { - s.expandWildcards = expandWildcards - return s -} - -func (r *SearchRequest) Scroll(scroll string) *SearchRequest { - r.scroll = scroll - return r -} - -func (r *SearchRequest) SearchSource(searchSource *SearchSource) *SearchRequest { - return r.Source(searchSource) -} - -func (r *SearchRequest) Source(source interface{}) *SearchRequest { - r.source = source - return r -} - -// 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.2/search-multi-search.html -func (r *SearchRequest) header() interface{} { - h := make(map[string]interface{}) - if r.searchType != "" { - h["search_type"] = r.searchType - } - - switch len(r.indices) { - case 0: - case 1: - h["index"] = r.indices[0] - default: - h["indices"] = r.indices - } - - switch len(r.types) { - case 0: - case 1: - h["type"] = r.types[0] - default: - h["types"] = r.types - } - - if r.routing != nil && *r.routing != "" { - h["routing"] = *r.routing - } - if r.preference != nil && *r.preference != "" { - h["preference"] = *r.preference - } - if r.requestCache != nil { - h["request_cache"] = *r.requestCache - } - if r.ignoreUnavailable != nil { - h["ignore_unavailable"] = *r.ignoreUnavailable - } - if r.allowNoIndices != nil { - h["allow_no_indices"] = *r.allowNoIndices - } - if r.expandWildcards != "" { - h["expand_wildcards"] = r.expandWildcards - } - if r.scroll != "" { - h["scroll"] = r.scroll - } - - return h -} - -// Body allows to access the search body of the request, as generated by the DSL. -// Notice that Body is read-only. You must not change the request body. -// -// 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.2/search-multi-search.html -func (r *SearchRequest) Body() (string, error) { - switch t := r.source.(type) { - default: - body, err := json.Marshal(r.source) - if err != nil { - return "", err - } - return string(body), nil - case *SearchSource: - src, err := t.Source() - if err != nil { - return "", err - } - body, err := json.Marshal(src) - if err != nil { - return "", err - } - return string(body), nil - case json.RawMessage: - return string(t), nil - case *json.RawMessage: - return string(*t), nil - case string: - return t, nil - case *string: - if t != nil { - return *t, nil - } - return "{}", nil - } -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/tasks_cancel.go b/vendor/gopkg.in/olivere/elastic.v6/tasks_cancel.go deleted file mode 100644 index 84f8aec..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/tasks_cancel.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 ( - "context" - "fmt" - "net/url" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// TasksCancelService can cancel long-running tasks. -// It is supported as of Elasticsearch 2.3.0. -// -// See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/tasks-cancel.html -// for details. -type TasksCancelService struct { - client *Client - pretty bool - taskId *int64 - actions []string - nodeId []string - parentNode string - parentTask *int64 -} - -// NewTasksCancelService creates a new TasksCancelService. -func NewTasksCancelService(client *Client) *TasksCancelService { - return &TasksCancelService{ - client: client, - actions: make([]string, 0), - nodeId: make([]string, 0), - } -} - -// TaskId specifies the task to cancel. Set to -1 to cancel all tasks. -func (s *TasksCancelService) TaskId(taskId int64) *TasksCancelService { - s.taskId = &taskId - return s -} - -// Actions is a list of actions that should be cancelled. Leave empty to cancel all. -func (s *TasksCancelService) Actions(actions []string) *TasksCancelService { - s.actions = actions - return s -} - -// NodeId is a list of node IDs or names to limit the returned information; -// use `_local` to return information from the node you're connecting to, -// leave empty to get information from all nodes. -func (s *TasksCancelService) NodeId(nodeId []string) *TasksCancelService { - s.nodeId = nodeId - return s -} - -// ParentNode specifies to cancel tasks with specified parent node. -func (s *TasksCancelService) ParentNode(parentNode string) *TasksCancelService { - s.parentNode = parentNode - return s -} - -// ParentTask specifies to cancel tasks with specified parent task id. -// Set to -1 to cancel all. -func (s *TasksCancelService) ParentTask(parentTask int64) *TasksCancelService { - s.parentTask = &parentTask - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *TasksCancelService) Pretty(pretty bool) *TasksCancelService { - s.pretty = pretty - return s -} - -// buildURL builds the URL for the operation. -func (s *TasksCancelService) buildURL() (string, url.Values, error) { - // Build URL - var err error - var path string - if s.taskId != nil { - path, err = uritemplates.Expand("/_tasks/{task_id}/_cancel", map[string]string{ - "task_id": fmt.Sprintf("%d", *s.taskId), - }) - } else { - path = "/_tasks/_cancel" - } - if err != nil { - return "", url.Values{}, err - } - - // Add query string parameters - params := url.Values{} - if s.pretty { - params.Set("pretty", "true") - } - if len(s.actions) > 0 { - params.Set("actions", strings.Join(s.actions, ",")) - } - if len(s.nodeId) > 0 { - params.Set("node_id", strings.Join(s.nodeId, ",")) - } - if s.parentNode != "" { - params.Set("parent_node", s.parentNode) - } - if s.parentTask != nil { - params.Set("parent_task", fmt.Sprintf("%v", *s.parentTask)) - } - return path, params, nil -} - -// Validate checks if the operation is valid. -func (s *TasksCancelService) Validate() error { - return nil -} - -// Do executes the operation. -func (s *TasksCancelService) Do(ctx context.Context) (*TasksListResponse, 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, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - }) - if err != nil { - return nil, err - } - - // Return operation response - ret := new(TasksListResponse) - 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.v6/tasks_get_task.go b/vendor/gopkg.in/olivere/elastic.v6/tasks_get_task.go deleted file mode 100644 index 5f63726..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/tasks_get_task.go +++ /dev/null @@ -1,108 +0,0 @@ -package elastic - -import ( - "context" - "fmt" - "net/url" - - "github.com/olivere/elastic/uritemplates" -) - -// TasksGetTaskService retrieves the state of a task in the cluster. It is part of the Task Management API -// documented at http://www.elastic.co/guide/en/elasticsearch/reference/5.2/tasks-list.html. -// -// It is supported as of Elasticsearch 2.3.0. -type TasksGetTaskService struct { - client *Client - pretty bool - taskId string - waitForCompletion *bool -} - -// NewTasksGetTaskService creates a new TasksGetTaskService. -func NewTasksGetTaskService(client *Client) *TasksGetTaskService { - return &TasksGetTaskService{ - client: client, - } -} - -// TaskId indicates to return the task with specified id. -func (s *TasksGetTaskService) TaskId(taskId string) *TasksGetTaskService { - s.taskId = taskId - return s -} - -// WaitForCompletion indicates whether to wait for the matching tasks -// to complete (default: false). -func (s *TasksGetTaskService) WaitForCompletion(waitForCompletion bool) *TasksGetTaskService { - s.waitForCompletion = &waitForCompletion - return s -} - -// Pretty indicates that the JSON response be indented and human readable. -func (s *TasksGetTaskService) Pretty(pretty bool) *TasksGetTaskService { - s.pretty = pretty - return s -} - -// buildURL builds the URL for the operation. -func (s *TasksGetTaskService) buildURL() (string, url.Values, error) { - // Build URL - path, err := uritemplates.Expand("/_tasks/{task_id}", map[string]string{ - "task_id": s.taskId, - }) - if err != nil { - return "", url.Values{}, err - } - - // Add query string parameters - params := url.Values{} - if s.pretty { - params.Set("pretty", "1") - } - if s.waitForCompletion != nil { - params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion)) - } - return path, params, nil -} - -// Validate checks if the operation is valid. -func (s *TasksGetTaskService) Validate() error { - return nil -} - -// Do executes the operation. -func (s *TasksGetTaskService) Do(ctx context.Context) (*TasksGetTaskResponse, 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, PerformRequestOptions{ - Method: "GET", - Path: path, - Params: params, - }) - if err != nil { - return nil, err - } - - // Return operation response - ret := new(TasksGetTaskResponse) - if err := s.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -type TasksGetTaskResponse struct { - Completed bool `json:"completed"` - Task *TaskInfo `json:"task,omitempty"` -} diff --git a/vendor/gopkg.in/olivere/elastic.v6/update.go b/vendor/gopkg.in/olivere/elastic.v6/update.go deleted file mode 100644 index c8ae2af..0000000 --- a/vendor/gopkg.in/olivere/elastic.v6/update.go +++ /dev/null @@ -1,330 +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" - "net/url" - "strings" - - "github.com/olivere/elastic/uritemplates" -) - -// UpdateService updates a document in Elasticsearch. -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-update.html -// for details. -type UpdateService struct { - client *Client - index string - typ string - id string - routing string - parent string - script *Script - fields []string - fsc *FetchSourceContext - version *int64 - versionType string - retryOnConflict *int - refresh string - waitForActiveShards string - upsert interface{} - scriptedUpsert *bool - docAsUpsert *bool - detectNoop *bool - doc interface{} - timeout string - pretty bool -} - -// NewUpdateService creates the service to update documents in Elasticsearch. -func NewUpdateService(client *Client) *UpdateService { - builder := &UpdateService{ - client: client, - fields: make([]string, 0), - } - return builder -} - -// Index is the name of the Elasticsearch index (required). -func (b *UpdateService) Index(name string) *UpdateService { - b.index = name - return b -} - -// Type is the type of the document (required). -func (b *UpdateService) Type(typ string) *UpdateService { - b.typ = typ - return b -} - -// Id is the identifier of the document to update (required). -func (b *UpdateService) Id(id string) *UpdateService { - b.id = id - return b -} - -// Routing specifies a specific routing value. -func (b *UpdateService) Routing(routing string) *UpdateService { - b.routing = routing - return b -} - -// Parent sets the id of the parent document. -func (b *UpdateService) Parent(parent string) *UpdateService { - b.parent = parent - return b -} - -// Script is the script definition. -func (b *UpdateService) Script(script *Script) *UpdateService { - b.script = script - return b -} - -// RetryOnConflict specifies how many times the operation should be retried -// when a conflict occurs (default: 0). -func (b *UpdateService) RetryOnConflict(retryOnConflict int) *UpdateService { - b.retryOnConflict = &retryOnConflict - return b -} - -// Fields is a list of fields to return in the response. -func (b *UpdateService) Fields(fields ...string) *UpdateService { - b.fields = make([]string, 0, len(fields)) - b.fields = append(b.fields, fields...) - return b -} - -// Version defines the explicit version number for concurrency control. -func (b *UpdateService) Version(version int64) *UpdateService { - b.version = &version - return b -} - -// VersionType is e.g. "internal". -func (b *UpdateService) VersionType(versionType string) *UpdateService { - b.versionType = versionType - return b -} - -// Refresh the index after performing the update. -// -// See https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-refresh.html -// for details. -func (b *UpdateService) Refresh(refresh string) *UpdateService { - b.refresh = refresh - return b -} - -// WaitForActiveShards sets the number of shard copies that must be active before -// proceeding with the update operation. Defaults to 1, meaning the primary shard only. -// Set to `all` for all shard copies, otherwise set to any non-negative value less than -// or equal to the total number of copies for the shard (number of replicas + 1). -func (b *UpdateService) WaitForActiveShards(waitForActiveShards string) *UpdateService { - b.waitForActiveShards = waitForActiveShards - return b -} - -// Doc allows for updating a partial document. -func (b *UpdateService) Doc(doc interface{}) *UpdateService { - b.doc = doc - return b -} - -// Upsert can be used to index the document when it doesn't exist yet. -// Use this e.g. to initialize a document with a default value. -func (b *UpdateService) Upsert(doc interface{}) *UpdateService { - b.upsert = doc - return b -} - -// DocAsUpsert can be used to insert the document if it doesn't already exist. -func (b *UpdateService) DocAsUpsert(docAsUpsert bool) *UpdateService { - b.docAsUpsert = &docAsUpsert - return b -} - -// DetectNoop will instruct Elasticsearch to check if changes will occur -// when updating via Doc. It there aren't any changes, the request will -// turn into a no-op. -func (b *UpdateService) DetectNoop(detectNoop bool) *UpdateService { - b.detectNoop = &detectNoop - return b -} - -// ScriptedUpsert should be set to true if the referenced script -// (defined in Script or ScriptId) should be called to perform an insert. -// The default is false. -func (b *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService { - b.scriptedUpsert = &scriptedUpsert - return b -} - -// Timeout is an explicit timeout for the operation, e.g. "1000", "1s" or "500ms". -func (b *UpdateService) Timeout(timeout string) *UpdateService { - b.timeout = timeout - return b -} - -// Pretty instructs to return human readable, prettified JSON. -func (b *UpdateService) Pretty(pretty bool) *UpdateService { - b.pretty = pretty - return b -} - -// FetchSource asks Elasticsearch to return the updated _source in the response. -func (s *UpdateService) FetchSource(fetchSource bool) *UpdateService { - if s.fsc == nil { - s.fsc = NewFetchSourceContext(fetchSource) - } else { - s.fsc.SetFetchSource(fetchSource) - } - return s -} - -// FetchSourceContext indicates that _source should be returned in the response, -// allowing wildcard patterns to be defined via FetchSourceContext. -func (s *UpdateService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *UpdateService { - s.fsc = fetchSourceContext - return s -} - -// url returns the URL part of the document request. -func (b *UpdateService) url() (string, url.Values, error) { - // Build url - path := "/{index}/{type}/{id}/_update" - path, err := uritemplates.Expand(path, map[string]string{ - "index": b.index, - "type": b.typ, - "id": b.id, - }) - if err != nil { - return "", url.Values{}, err - } - - // Parameters - params := make(url.Values) - if b.pretty { - params.Set("pretty", "true") - } - if b.routing != "" { - params.Set("routing", b.routing) - } - if b.parent != "" { - params.Set("parent", b.parent) - } - if b.timeout != "" { - params.Set("timeout", b.timeout) - } - if b.refresh != "" { - params.Set("refresh", b.refresh) - } - if b.waitForActiveShards != "" { - params.Set("wait_for_active_shards", b.waitForActiveShards) - } - if len(b.fields) > 0 { - params.Set("fields", strings.Join(b.fields, ",")) - } - if b.version != nil { - params.Set("version", fmt.Sprintf("%d", *b.version)) - } - if b.versionType != "" { - params.Set("version_type", b.versionType) - } - if b.retryOnConflict != nil { - params.Set("retry_on_conflict", fmt.Sprintf("%v", *b.retryOnConflict)) - } - - return path, params, nil -} - -// body returns the body part of the document request. -func (b *UpdateService) body() (interface{}, error) { - source := make(map[string]interface{}) - - if b.script != nil { - src, err := b.script.Source() - if err != nil { - return nil, err - } - source["script"] = src - } - - if b.scriptedUpsert != nil { - source["scripted_upsert"] = *b.scriptedUpsert - } - - if b.upsert != nil { - source["upsert"] = b.upsert - } - - if b.doc != nil { - source["doc"] = b.doc - } - if b.docAsUpsert != nil { - source["doc_as_upsert"] = *b.docAsUpsert - } - if b.detectNoop != nil { - source["detect_noop"] = *b.detectNoop - } - if b.fsc != nil { - src, err := b.fsc.Source() - if err != nil { - return nil, err - } - source["_source"] = src - } - - return source, nil -} - -// Do executes the update operation. -func (b *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) { - path, params, err := b.url() - if err != nil { - return nil, err - } - - // Get body of the request - body, err := b.body() - if err != nil { - return nil, err - } - - // Get response - res, err := b.client.PerformRequest(ctx, PerformRequestOptions{ - Method: "POST", - Path: path, - Params: params, - Body: body, - }) - if err != nil { - return nil, err - } - - // Return result - ret := new(UpdateResponse) - if err := b.client.decoder.Decode(res.Body, ret); err != nil { - return nil, err - } - return ret, nil -} - -// 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"` - 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/modules.txt b/vendor/modules.txt new file mode 100644 index 0000000..fd1f59e --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,11 @@ +# github.com/mailru/easyjson v0.7.1 +github.com/mailru/easyjson +github.com/mailru/easyjson/jlexer +github.com/mailru/easyjson/jwriter +github.com/mailru/easyjson/buffer +# github.com/olivere/elastic/v7 v7.0.15 +github.com/olivere/elastic/v7 +github.com/olivere/elastic/v7/config +github.com/olivere/elastic/v7/uritemplates +# github.com/pkg/errors v0.9.1 +github.com/pkg/errors diff --git a/vendor/vendor.json b/vendor/vendor.json deleted file mode 100644 index caf2978..0000000 --- a/vendor/vendor.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "comment": "", - "ignore": "test", - "package": [ - { - "checksumSHA1": "Ckkk75h7Xhrc3b+QJ3oqbIrGsaY=", - "path": "github.com/mailru/easyjson", - "revision": "03f2033d19d5860aef995fe360ac7d395cd8ce65", - "revisionTime": "2018-07-30T09:45:02Z" - }, - { - "checksumSHA1": "T8soMJArSZrYnhmdpAnq1bVxQ6Q=", - "path": "github.com/mailru/easyjson/buffer", - "revision": "03f2033d19d5860aef995fe360ac7d395cd8ce65", - "revisionTime": "2018-07-30T09:45:02Z" - }, - { - "checksumSHA1": "zErZOOMVWCO/Z1WGWBAG9VdccQc=", - "path": "github.com/mailru/easyjson/jlexer", - "revision": "03f2033d19d5860aef995fe360ac7d395cd8ce65", - "revisionTime": "2018-07-30T09:45:02Z" - }, - { - "checksumSHA1": "4BAeeJ7JywEQyR6GqRrxfSfN2/Q=", - "path": "github.com/mailru/easyjson/jwriter", - "revision": "03f2033d19d5860aef995fe360ac7d395cd8ce65", - "revisionTime": "2018-07-30T09:45:02Z" - }, - { - "checksumSHA1": "v/phfIsGFjsgpJqe4BEKbGmMYAY=", - "path": "github.com/olivere/elastic/config", - "revision": "3a15a1301c4bf0bb5a4eb3f5a65331912ae25ef0", - "revisionTime": "2018-08-02T18:54:02Z" - }, - { - "checksumSHA1": "AmcqvKDAUGvVsrf8NDCQ/B8cMj4=", - "path": "github.com/olivere/elastic/uritemplates", - "revision": "3a15a1301c4bf0bb5a4eb3f5a65331912ae25ef0", - "revisionTime": "2018-08-02T18:54:02Z" - }, - { - "checksumSHA1": "ljd3FhYRJ91cLZz3wsH9BQQ2JbA=", - "path": "github.com/pkg/errors", - "revision": "816c9085562cd7ee03e7f8188a1cfd942858cded", - "revisionTime": "2018-03-11T21:45:15Z" - }, - { - "checksumSHA1": "W70ayHguz9qyWgVlL+SH/xeYruc=", - "path": "gopkg.in/olivere/elastic.v6", - "revision": "e3492b022a109ac0e52a6d42d5bfb835050fa7f4", - "revisionTime": "2018-08-02T18:23:21Z" - } - ], - "rootPath": "git.autistici.org/ai/logcat" -} -- GitLab