Skip to content

Commit d9bf375

Browse files
jsvdJAndritschrobbaveykarenzone
authored
Introduce cursor tracking akin to jdbc input (#205)
Provide field value tracking, persisted to disk on each search_after page. Adds `:last_value` and `:present` placeholders, allowing the plugin to inject the cursor value and now-30 seconds, respectively, in the query string. Useful to track new data being written to an index or series of indices. Works best with nano second precision timestamps added by Elasticsearch's Ingest Pipelines. --------- Co-authored-by: Joel Andritsch <[email protected]> Co-authored-by: Rob Bavey <[email protected]> Co-authored-by: Karen Metts <[email protected]>
1 parent 7f8120c commit d9bf375

10 files changed

+411
-16
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
## 5.1.0
2+
- Add "cursor"-like index tracking [#205](https://github.com/logstash-plugins/logstash-input-elasticsearch/pull/205)
3+
14
## 5.0.2
25
- Add elastic-transport client support used in elasticsearch-ruby 8.x [#223](https://github.com/logstash-plugins/logstash-input-elasticsearch/pull/223)
36

docs/index.asciidoc

+178-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ This would create an Elasticsearch query with the following format:
4848
"sort": [ "_doc" ]
4949
}'
5050

51-
51+
[id="plugins-{type}s-{plugin}-scheduling"]
5252
==== Scheduling
5353

5454
Input from this plugin can be scheduled to run periodically according to a specific
@@ -103,6 +103,133 @@ Common causes are:
103103
- When the hit result contains top-level fields that are {logstash-ref}/processing.html#reserved-fields[reserved in Logstash] but do not have the expected shape. Use the <<plugins-{type}s-{plugin}-target>> directive to avoid conflicts with the top-level namespace.
104104
- When <<plugins-{type}s-{plugin}-docinfo>> is enabled and the docinfo fields cannot be merged into the hit result. Combine <<plugins-{type}s-{plugin}-target>> and <<plugins-{type}s-{plugin}-docinfo_target>> to avoid conflict.
105105

106+
[id="plugins-{type}s-{plugin}-cursor"]
107+
==== Tracking a field's value across runs
108+
109+
.Technical Preview: Tracking a field's value
110+
****
111+
The feature that allows tracking a field's value across runs is in _Technical Preview_.
112+
Configuration options and implementation details are subject to change in minor releases without being preceded by deprecation warnings.
113+
****
114+
115+
Some uses cases require tracking the value of a particular field between two jobs.
116+
Examples include:
117+
118+
* avoiding the need to re-process the entire result set of a long query after an unplanned restart
119+
* grabbing only new data from an index instead of processing the entire set on each job.
120+
121+
The Elasticsearch input plugin provides the <<plugins-{type}s-{plugin}-tracking_field>> and <<plugins-{type}s-{plugin}-tracking_field_seed>> options.
122+
When <<plugins-{type}s-{plugin}-tracking_field>> is set, the plugin records the value of that field for the last document retrieved in a run into
123+
a file.
124+
(The file location defaults to <<plugins-{type}s-{plugin}-last_run_metadata_path>>.)
125+
126+
You can then inject this value in the query using the placeholder `:last_value`.
127+
The value will be injected into the query before execution, and then updated after the query completes if new data was found.
128+
129+
This feature works best when:
130+
131+
* the query sorts by the tracking field,
132+
* the timestamp field is added by {es}, and
133+
* the field type has enough resolution so that two events are unlikely to have the same value.
134+
135+
Consider using a tracking field whose type is https://www.elastic.co/guide/en/elasticsearch/reference/current/date_nanos.html[date nanoseconds].
136+
If the tracking field is of this data type, you can use an extra placeholder called `:present` to inject the nano-second based value of "now-30s".
137+
This placeholder is useful as the right-hand side of a range filter, allowing the collection of
138+
new data but leaving partially-searchable bulk request data to the next scheduled job.
139+
140+
[id="plugins-{type}s-{plugin}-tracking-sample"]
141+
===== Sample configuration: Track field value across runs
142+
143+
This section contains a series of steps to help you set up the "tailing" of data being written to a set of indices, using a date nanosecond field added by an Elasticsearch ingest pipeline and the `tracking_field` capability of this plugin.
144+
145+
. Create ingest pipeline that adds Elasticsearch's `_ingest.timestamp` field to the documents as `event.ingested`:
146+
+
147+
[source, json]
148+
PUT _ingest/pipeline/my-pipeline
149+
{
150+
"processors": [
151+
{
152+
"script": {
153+
"lang": "painless",
154+
"source": "ctx.putIfAbsent(\"event\", [:]); ctx.event.ingested = metadata().now.format(DateTimeFormatter.ISO_INSTANT);"
155+
}
156+
}
157+
]
158+
}
159+
160+
[start=2]
161+
. Create an index mapping where the tracking field is of date nanosecond type and invokes the defined pipeline:
162+
+
163+
[source, json]
164+
PUT /_template/my_template
165+
{
166+
"index_patterns": ["test-*"],
167+
"settings": {
168+
"index.default_pipeline": "my-pipeline",
169+
},
170+
"mappings": {
171+
"properties": {
172+
"event": {
173+
"properties": {
174+
"ingested": {
175+
"type": "date_nanos",
176+
"format": "strict_date_optional_time_nanos"
177+
}
178+
}
179+
}
180+
}
181+
}
182+
}
183+
184+
[start=3]
185+
. Define a query that looks at all data of the indices, sorted by the tracking field, and with a range filter since the last value seen until present:
186+
+
187+
[source,json]
188+
{
189+
"query": {
190+
"range": {
191+
"event.ingested": {
192+
"gt": ":last_value",
193+
"lt": ":present"
194+
}
195+
}
196+
},
197+
"sort": [
198+
{
199+
"event.ingested": {
200+
"order": "asc",
201+
"format": "strict_date_optional_time_nanos",
202+
"numeric_type": "date_nanos"
203+
}
204+
}
205+
]
206+
}
207+
208+
[start=4]
209+
. Configure the Elasticsearch input to query the indices with the query defined above, every minute, and track the `event.ingested` field:
210+
+
211+
[source, ruby]
212+
input {
213+
elasticsearch {
214+
id => tail_test_index
215+
hosts => [ 'https://..']
216+
api_key => '....'
217+
index => 'test-*'
218+
query => '{ "query": { "range": { "event.ingested": { "gt": ":last_value", "lt": ":present"}}}, "sort": [ { "event.ingested": {"order": "asc", "format": "strict_date_optional_time_nanos", "numeric_type" : "date_nanos" } } ] }'
219+
tracking_field => "[event][ingested]"
220+
slices => 5 # optional use of slices to speed data processing, should be equal to or less than number of primary shards
221+
schedule => '* * * * *' # every minute
222+
schedule_overlap => false # don't accumulate jobs if one takes longer than 1 minute
223+
}
224+
}
225+
226+
With this sample setup, new documents are indexed into a `test-*` index.
227+
The next scheduled run:
228+
229+
* selects all new documents since the last observed value of the tracking field,
230+
* uses {ref}/point-in-time-api.html#point-in-time-api[Point in time (PIT)] + {ref}/paginate-search-results.html#search-after[Search after] to paginate through all the data, and
231+
* updates the value of the field at the end of the pagination.
232+
106233
[id="plugins-{type}s-{plugin}-options"]
107234
==== Elasticsearch Input configuration options
108235

@@ -126,12 +253,14 @@ Please check out <<plugins-{type}s-{plugin}-obsolete-options>> for details.
126253
| <<plugins-{type}s-{plugin}-ecs_compatibility>> |<<string,string>>|No
127254
| <<plugins-{type}s-{plugin}-hosts>> |<<array,array>>|No
128255
| <<plugins-{type}s-{plugin}-index>> |<<string,string>>|No
256+
| <<plugins-{type}s-{plugin}-last_run_metadata_path>> |<<string,string>>|No
129257
| <<plugins-{type}s-{plugin}-password>> |<<password,password>>|No
130258
| <<plugins-{type}s-{plugin}-proxy>> |<<uri,uri>>|No
131259
| <<plugins-{type}s-{plugin}-query>> |<<string,string>>|No
132260
| <<plugins-{type}s-{plugin}-response_type>> |<<string,string>>, one of `["hits","aggregations"]`|No
133261
| <<plugins-{type}s-{plugin}-request_timeout_seconds>> | <<number,number>>|No
134262
| <<plugins-{type}s-{plugin}-schedule>> |<<string,string>>|No
263+
| <<plugins-{type}s-{plugin}-schedule_overlap>> |<<boolean,boolean>>|No
135264
| <<plugins-{type}s-{plugin}-scroll>> |<<string,string>>|No
136265
| <<plugins-{type}s-{plugin}-search_api>> |<<string,string>>, one of `["auto", "search_after", "scroll"]`|No
137266
| <<plugins-{type}s-{plugin}-size>> |<<number,number>>|No
@@ -151,6 +280,8 @@ Please check out <<plugins-{type}s-{plugin}-obsolete-options>> for details.
151280
| <<plugins-{type}s-{plugin}-ssl_verification_mode>> |<<string,string>>, one of `["full", "none"]`|No
152281
| <<plugins-{type}s-{plugin}-socket_timeout_seconds>> | <<number,number>>|No
153282
| <<plugins-{type}s-{plugin}-target>> | {logstash-ref}/field-references-deepdive.html[field reference] | No
283+
| <<plugins-{type}s-{plugin}-tracking_field>> |<<string,string>>|No
284+
| <<plugins-{type}s-{plugin}-tracking_field_seed>> |<<string,string>>|No
154285
| <<plugins-{type}s-{plugin}-retries>> | <<number,number>>|No
155286
| <<plugins-{type}s-{plugin}-user>> |<<string,string>>|No
156287
|=======================================================================
@@ -330,6 +461,17 @@ Check out {ref}/api-conventions.html#api-multi-index[Multi Indices
330461
documentation] in the Elasticsearch documentation for info on
331462
referencing multiple indices.
332463

464+
[id="plugins-{type}s-{plugin}-last_run_metadata_path"]
465+
===== `last_run_metadata_path`
466+
467+
* Value type is <<string,string>>
468+
* There is no default value for this setting.
469+
470+
The path to store the last observed value of the tracking field, when used.
471+
By default this file is stored as `<path.data>/plugins/inputs/elasticsearch/<pipeline_id>/last_run_value`.
472+
473+
This setting should point to file, not a directory, and Logstash must have read+write access to this file.
474+
333475
[id="plugins-{type}s-{plugin}-password"]
334476
===== `password`
335477

@@ -410,6 +552,19 @@ for example: "* * * * *" (execute query every minute, on the minute)
410552
There is no schedule by default. If no schedule is given, then the statement is run
411553
exactly once.
412554

555+
[id="plugins-{type}s-{plugin}-schedule_overlap"]
556+
===== `schedule_overlap`
557+
558+
* Value type is <<boolean,boolean>>
559+
* Default value is `true`
560+
561+
Whether to allow queuing of a scheduled run if a run is occurring.
562+
While this is ideal for ensuring a new run happens immediately after the previous on finishes if there
563+
is a lot of work to do, but given the queue is unbounded it may lead to an out of memory over long periods of time
564+
if the queue grows continuously.
565+
566+
When in doubt, set `schedule_overlap` to false (it may become the default value in the future).
567+
413568
[id="plugins-{type}s-{plugin}-scroll"]
414569
===== `scroll`
415570

@@ -622,6 +777,28 @@ When the `target` is set to a field reference, the `_source` of the hit is place
622777
This option can be useful to avoid populating unknown fields when a downstream schema such as ECS is enforced.
623778
It is also possible to target an entry in the event's metadata, which will be available during event processing but not exported to your outputs (e.g., `target \=> "[@metadata][_source]"`).
624779

780+
[id="plugins-{type}s-{plugin}-tracking_field"]
781+
===== `tracking_field`
782+
783+
* Value type is <<string,string>>
784+
* There is no default value for this setting.
785+
786+
Which field from the last event of a previous run will be used a cursor value for the following run.
787+
The value of this field is injected into each query if the query uses the placeholder `:last_value`.
788+
For the first query after a pipeline is started, the value used is either read from <<plugins-{type}s-{plugin}-last_run_metadata_path>> file,
789+
or taken from <<plugins-{type}s-{plugin}-tracking_field_seed>> setting.
790+
791+
Note: The tracking value is updated after each page is read and at the end of each Point in Time. In case of a crash the last saved value will be used so some duplication of data can occur. For this reason the use of unique document IDs for each event is recommended in the downstream destination.
792+
793+
[id="plugins-{type}s-{plugin}-tracking_field_seed"]
794+
===== `tracking_field_seed`
795+
796+
* Value type is <<string,string>>
797+
* Default value is `"1970-01-01T00:00:00.000000000Z"`
798+
799+
The starting value for the <<plugins-{type}s-{plugin}-tracking_field>> if there is no <<plugins-{type}s-{plugin}-last_run_metadata_path>> already.
800+
This field defaults to the nanosecond precision ISO8601 representation of `epoch`, or "1970-01-01T00:00:00.000000000Z", given nano-second precision timestamps are the
801+
most reliable data format to use for this feature.
625802

626803
[id="plugins-{type}s-{plugin}-user"]
627804
===== `user`

lib/logstash/inputs/elasticsearch.rb

+62-2
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ class LogStash::Inputs::Elasticsearch < LogStash::Inputs::Base
7373

7474
require 'logstash/inputs/elasticsearch/paginated_search'
7575
require 'logstash/inputs/elasticsearch/aggregation'
76+
require 'logstash/inputs/elasticsearch/cursor_tracker'
7677

7778
include LogStash::PluginMixins::ECSCompatibilitySupport(:disabled, :v1, :v8 => :v1)
7879
include LogStash::PluginMixins::ECSCompatibilitySupport::TargetCheck
@@ -124,6 +125,20 @@ class LogStash::Inputs::Elasticsearch < LogStash::Inputs::Base
124125
# by this pipeline input.
125126
config :slices, :validate => :number
126127

128+
# Enable tracking the value of a given field to be used as a cursor
129+
# Main concerns:
130+
# * using anything other than _event.timestamp easily leads to data loss
131+
# * the first "synchronization run can take a long time"
132+
config :tracking_field, :validate => :string
133+
134+
# Define the initial seed value of the tracking_field
135+
config :tracking_field_seed, :validate => :string, :default => "1970-01-01T00:00:00.000000000Z"
136+
137+
# The location of where the tracking field value will be stored
138+
# The value is persisted after each scheduled run (and not per result)
139+
# If it's not set it defaults to '${path.data}/plugins/inputs/elasticsearch/<pipeline_id>/last_run_value'
140+
config :last_run_metadata_path, :validate => :string
141+
127142
# If set, include Elasticsearch document information such as index, type, and
128143
# the id in the event.
129144
#
@@ -250,6 +265,10 @@ class LogStash::Inputs::Elasticsearch < LogStash::Inputs::Base
250265
# exactly once.
251266
config :schedule, :validate => :string
252267

268+
# Allow scheduled runs to overlap (enabled by default). Setting to false will
269+
# only start a new scheduled run after the previous one completes.
270+
config :schedule_overlap, :validate => :boolean
271+
253272
# If set, the _source of each hit will be added nested under the target instead of at the top-level
254273
config :target, :validate => :field_reference
255274

@@ -328,16 +347,30 @@ def register
328347

329348
setup_query_executor
330349

350+
setup_cursor_tracker
351+
331352
@client
332353
end
333354

334355
def run(output_queue)
335356
if @schedule
336-
scheduler.cron(@schedule) { @query_executor.do_run(output_queue) }
357+
scheduler.cron(@schedule, :overlap => @schedule_overlap) do
358+
@query_executor.do_run(output_queue, get_query_object())
359+
end
337360
scheduler.join
338361
else
339-
@query_executor.do_run(output_queue)
362+
@query_executor.do_run(output_queue, get_query_object())
363+
end
364+
end
365+
366+
def get_query_object
367+
if @cursor_tracker
368+
query = @cursor_tracker.inject_cursor(@query)
369+
@logger.debug("new query is #{query}")
370+
else
371+
query = @query
340372
end
373+
LogStash::Json.load(query)
341374
end
342375

343376
##
@@ -347,6 +380,11 @@ def push_hit(hit, output_queue, root_field = '_source')
347380
event = event_from_hit(hit, root_field)
348381
decorate(event)
349382
output_queue << event
383+
record_last_value(event)
384+
end
385+
386+
def record_last_value(event)
387+
@cursor_tracker.record_last_value(event) if @tracking_field
350388
end
351389

352390
def event_from_hit(hit, root_field)
@@ -640,6 +678,28 @@ def setup_query_executor
640678
end
641679
end
642680

681+
def setup_cursor_tracker
682+
return unless @tracking_field
683+
return unless @query_executor.is_a?(LogStash::Inputs::Elasticsearch::SearchAfter)
684+
685+
if @resolved_search_api != "search_after" || @response_type != "hits"
686+
raise ConfigurationError.new("The `tracking_field` feature can only be used with `search_after` non-aggregation queries")
687+
end
688+
689+
@cursor_tracker = CursorTracker.new(last_run_metadata_path: last_run_metadata_path,
690+
tracking_field: @tracking_field,
691+
tracking_field_seed: @tracking_field_seed)
692+
@query_executor.cursor_tracker = @cursor_tracker
693+
end
694+
695+
def last_run_metadata_path
696+
return @last_run_metadata_path if @last_run_metadata_path
697+
698+
last_run_metadata_path = ::File.join(LogStash::SETTINGS.get_value("path.data"), "plugins", "inputs", "elasticsearch", pipeline_id, "last_run_value")
699+
FileUtils.mkdir_p ::File.dirname(last_run_metadata_path)
700+
last_run_metadata_path
701+
end
702+
643703
def get_transport_client_class
644704
# LS-core includes `elasticsearch` gem. The gem is composed of two separate gems: `elasticsearch-api` and `elasticsearch-transport`
645705
# And now `elasticsearch-transport` is old, instead we have `elastic-transport`.

lib/logstash/inputs/elasticsearch/aggregation.rb

+11-8
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,9 @@ def initialize(client, plugin)
1212
@client = client
1313
@plugin_params = plugin.params
1414

15+
@index = @plugin_params["index"]
1516
@size = @plugin_params["size"]
16-
@query = @plugin_params["query"]
1717
@retries = @plugin_params["retries"]
18-
@agg_options = {
19-
:index => @plugin_params["index"],
20-
:size => 0
21-
}.merge(:body => @query)
22-
2318
@plugin = plugin
2419
end
2520

@@ -33,10 +28,18 @@ def retryable(job_name, &block)
3328
false
3429
end
3530

36-
def do_run(output_queue)
31+
def aggregation_options(query_object)
32+
{
33+
:index => @index,
34+
:size => 0,
35+
:body => query_object
36+
}
37+
end
38+
39+
def do_run(output_queue, query_object)
3740
logger.info("Aggregation starting")
3841
r = retryable(AGGREGATION_JOB) do
39-
@client.search(@agg_options)
42+
@client.search(aggregation_options(query_object))
4043
end
4144
@plugin.push_hit(r, output_queue, 'aggregations') if r
4245
end

0 commit comments

Comments
 (0)