如何结合查询与过滤器实现带时间限制的Syslog关键消息检索
Hey there! Looks like you're trying to pull relevant Syslog messages from Elasticsearch 6.2 by targeting error/warn/fatal/fail terms and adding a time range filter—great approach combining full-text search with filtering!
I noticed your initial query has a small syntax issue though: in Elasticsearch 6.2, you can't place a filter directly at the top level like that. Instead, you'll want to wrap your full-text query and time filter inside a bool query. This not only fixes the syntax but also ensures the time filter doesn't impact relevance scores (which is more efficient for filtering).
Here's the corrected, working query tailored to your needs:
GET /_search { "query": { "bool": { "must": [ { "query_string": { "default_field": "message", "query": "error OR warn OR fatal OR fail" } } ], "filter": [ { "range": { "timestamp": { "gte": "now-24h", // Adjust this to your desired time range "lte": "now" } } } ] } } }
Let me break this down for clarity:
- The
boolquery lets us combine multiple query/filter clauses cleanly. - The
mustclause holds your full-text search: it ensures only documents containing any of your target terms in themessagefield are included, and calculates relevance scores based on those matches. - The
filterclause adds the time range restriction—since filters are cached in Elasticsearch, this will make repeated queries faster. You can adjust thegtevalue to fit your needs:- Use
now-7dfor the last 7 days - Use
2024-05-01T00:00:00Zfor a specific start time - Add
lteif you need an end time (defaults tonowif omitted)
- Use
If you want to make the term matching case-insensitive (in case your Syslog messages mix uppercase/lowercase terms like Error or WARN), you can tweak the query_string to use lowercase terms and leverage your field's analyzer, or add lowercase_expanded_terms: true to the query_string settings.
内容的提问来源于stack exchange,提问作者Mickster

