Twitter (X) API to Elasticsearch: Mapping, Bulk Loader and Kibana

By TwitterAPI.io Team•16 min read
Diagram of the Twitter (X) API to Elasticsearch pipeline in five lanes: fetch with /twitter/tweet/advanced_search, shape createdAt to ISO 8601, map text, keyword, date, integer and long fields, bulk with helpers.bulk using the tweet id as _id, and query with match, date_histogram and terms aggregations in Kibana Lens.
Search, map, bulk, aggregate. Footer numbers come from 1,633 real posts collected in 2026.
TL;DR
  • Pipeline: /twitter/tweet/advanced_search pages (20 tweets each) -> trim -> helpers.bulk() with _id = tweet id -> date_histogram and terms aggregations -> Kibana Lens.
  • Map explicitly: createdAt does not match Elasticsearch's default dynamic date formats; convert it to ISO 8601 in Python (100.0% of 1,633 sampled values parsed with one pattern).
  • Types from real data: like and reply counts fit integer (max 5,253); give viewCount (max 14,133,482) and followers long for headroom.
  • Trim before bulk: a full tweet averages 5,867 bytes of NDJSON, a 20-field document 1,461 bytes; a 5 MB bulk request holds 893 vs 3,588 docs.
  • Text is long now: median post 287 characters, 51.4% over 280, longest 12,596; keep text as text, never keyword.
  • Cost: $0.15 per 1,000 tweets read on TwitterAPI.io vs $0.005 per post read ($5 per 1,000) on the official X API; an empty incremental check is the $0.00015 minimum.

This page is about one destination: an Elasticsearch index you query with full-text search and aggregations, then chart in Kibana. Our Twitter API to Splunk guide lands the same feed in a Splunk index through the HTTP Event Collector and SPL, and our Twitter API to PostgreSQL guide stores tweets in relational tables; pick this one if your team already runs Elasticsearch (or Elastic Cloud) and wants relevance-ranked search over post text plus Kibana dashboards.

Many of the search results for this topic are tutorials built on the Logstash Twitter input or the old Elasticsearch Twitter river, both tied to free access to X's streaming API that no longer exists in that form. The approach below does not depend on either: a small Python loop reads tweets over HTTPS, shapes them into documents and bulk-indexes them. No X account is needed for the reads.

Every type in the mapping below is backed by a measurement. We pulled 1,633 recent posts mentioning Elasticsearch, OpenSearch or Kibana and checked what an index would see: date strings, value ranges, optional fields, text length and the exact NDJSON bytes the bulk helper would send. We did not have an Elasticsearch cluster on the build machine, so index size on disk and indexing throughput are not measured here; everything we state about Elasticsearch behavior comes from the Elastic docs, quoted per section.

Bulk payload cut by trimming a tweet to 20 fields

75.1% smaller (5,867 -> 1,461 bytes)

01 — Section

Architecture: search, shape, bulk, aggregate

The pipeline has five steps, and only two of them touch Elasticsearch. Fetch: call GET https://api.twitterapi.io/twitter/tweet/advanced_search with a query and queryType=Latest; each page returns up to 20 tweets in a top-level tweets array plus has_next_page and next_cursor. Shape: keep the fields you will search or chart, convert the date, lowercase hashtags. Map: create the index once with an explicit mapping. Bulk: stream documents through helpers.bulk(). Query: run match, date_histogram and terms queries, or build the same views in Kibana Lens.

Why search and not a timeline call. A keyword or hashtag index is usually built from search, and the search operators include time windows: since_time:<unix> and until_time:<unix> inside the query string, per the twitterapi.io advanced search docs. That makes back-fills (step until_time backward) and incremental runs (start at the newest created_at you already indexed) the same loop. If you track a fixed list of organization accounts instead, /twitter/user/last_tweets with userName returns data.tweets[] with the same tweet fields.

Why bulk. Elasticsearch's bulk API takes newline-delimited JSON: one action line, one source line, repeated, and "the final line of data must end with a newline character", per the bulk API reference. The Python helper writes those lines for you. The same reference notes there is no "correct" number of actions per request and that the HTTP request size is capped at 100 MB by default, so batch size is something you tune; the payload numbers further down give you a starting point.

Idempotency for free. Use the tweet id as _id and keep the default index action. Per the bulk reference, an index action "adds or replaces a document as necessary", whereas create fails when the ID already exists. With index, a re-run after a crash or an overlapping incremental window refreshes like and view counts instead of creating duplicates.

02 — Section

The index mapping, field by field

You can let Elasticsearch guess types on the first document, but for tweets the guesses are poor. Per the dynamic field mapping docs, a string that fails date and numeric detection becomes a text field with a .keyword sub-field, and date detection only recognizes strict_date_optional_time and yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z by default. The API's createdAt looks like Thu Oct 16 12:34:56 +0000 2025, which matches neither, so it would be indexed as text and your date histogram would have nothing to bucket. Every other string (ids, language codes, handles) would carry an analyzed text copy you never search.

The mapping below sets dynamic: false: fields you did not declare stay in _source (you can still read them in hits) but are not indexed. That keeps the index small if the API adds fields later. Each choice is backed by the sample:

FieldTypeWhy (from the sample)
texttext59.6% of posts are longer than 256 characters; never a keyword
created_atdate100.0% of createdAt values parsed with one pattern, all +0000
likeCount and other countsintegerlargest like count 5,253, far below 2,147,483,647
viewCount, author.followerslonglargest values 14,133,482 and 2,503,070; headroom for viral posts
hashtags, lang, author.userNamekeywordlongest hashtag 26 characters; exact-match terms
urlskeyword, ignore_above 2048longest expanded URL 252 characters, close to 256

Integer vs long. Per the numeric field docs, integer is a signed 32-bit type (up to 2^31 - 1) and long a signed 64-bit type, and you "should pick the smallest type which is enough for your use-case"; the same page notes that storage size depends on the actual values, not the declared type. So long on viewCount costs no extra disk and protects you from the one viral post whose views pass 2.1 billion.

Why urls gets a high ignore_above. Strings longer than ignore_above "will not be indexed or stored" as terms, though they stay in _source, per the ignore_above docs. A limit of 256 is common in templates. In our sample the longest expanded URL was 252 characters, 0 of 1,369 URLs went over 256, but that is close enough to the line that a tracking-heavy link would silently drop out of a terms aggregation. 2048 removes the risk.

Dates: convert createdAt before indexing. Per the date field docs, a date field without a format accepts strict_date_optional_time||epoch_millis, converts values to UTC and stores them as milliseconds since the epoch. The simplest path is to hand it ISO 8601: parse createdAt once in Python and write 2025-10-16T12:34:56Z. You could declare a custom format on the field instead, but converting in Python keeps the source document readable in Discover and lets you catch a bad value before the bulk call rather than as a per-document mapper_parsing_exception in the bulk response.

What the sample showed. All 1,633 createdAt values parsed with the pattern %a %b %d %H:%M:%S %z %Y (0 failures), and every one carried the +0000 offset. So the conversion is a pure reformat with no time-zone arithmetic. Kibana then shows times in the browser's zone, while date_histogram buckets in UTC unless you pass time_zone.

json
PUT /tweets-elasticsearch
{
  "mappings": {
    "dynamic": false,
    "properties": {
      "id":             { "type": "keyword" },
      "url":            { "type": "keyword", "index": false },
      "text":           { "type": "text" },
      "lang":           { "type": "keyword" },
      "created_at":     { "type": "date" },
      "author": {
        "properties": {
          "id":             { "type": "keyword" },
          "userName":       { "type": "keyword" },
          "followers":      { "type": "long" },
          "isBlueVerified": { "type": "boolean" }
        }
      },
      "likeCount":      { "type": "integer" },
      "retweetCount":   { "type": "integer" },
      "replyCount":     { "type": "integer" },
      "quoteCount":     { "type": "integer" },
      "bookmarkCount":  { "type": "integer" },
      "viewCount":      { "type": "long" },
      "isReply":        { "type": "boolean" },
      "conversationId": { "type": "keyword" },
      "hashtags":       { "type": "keyword" },
      "urls":           { "type": "keyword", "ignore_above": 2048 },
      "media_types":    { "type": "keyword" },
      "is_quote":       { "type": "boolean" }
    }
  }
}
03 — Section

What a real tweet batch looks like to the index

Before sizing anything, it helps to know what the documents contain. Over 1,633 posts, the count fields were heavily skewed: a median post had 3 likes and 279 views, while the top post had 14,133,482 views. That skew matters for dashboards, because a sum of views is driven by a handful of posts; a median (a percentiles aggregation) or a terms split by author usually tells a better story.

Count fieldMedian99th pctMaxZero share
likeCount37065,25329.0%
retweetCount012481463.6%
replyCount13612548.3%
quoteCount0828785.1%
bookmarkCount06785,78558.8%
viewCount279115,79614,133,4820.2%

Optional parts were present in a minority of posts. Arrays like hashtags and urls simply come back empty; Elasticsearch indexes an empty array as no value, so no null handling is needed. Fields that never showed up (here, place) do not need a mapping at all.

Optional partPresent inMapping consequence
expanded URLs45.9%array of keyword; empty array is fine
media (photo, video, GIF)33.3%store media_types, not the media objects
replies (isReply)15.6%boolean filter for threads vs top-level posts
hashtags17.1%lowercase before indexing so #AI and #ai merge
user mentions14.7%skip unless you need a mention graph
quoted tweet11.3%keep a boolean, not the nested quoted object
place0.0%no geo_point field needed for this topic

Text length changes the mapping advice found in older tutorials. Long posts are common now: the median text in our sample was 287 characters, the 95th percentile 2,523, the longest 12,596, and 51.4% ran past the old 280-character limit. If text were mapped as keyword with ignore_above: 256, 59.6% of posts would be unsearchable as terms. Keep it as text (analyzed, full-text search), and if you need exact-phrase dedup add a hash field instead of a keyword copy of the body.

04 — Section

Sizing bulk requests: trim the tweet first

A raw API tweet carries far more than you index: the full author profile, entity offsets, media variants, and sometimes a complete quoted tweet. We serialized each sampled tweet exactly as the bulk helper sends it (one action line plus one source line) in two forms: the full API object, and the 20-field document from the mapping above.

Document formMedian bytesMean bytes95th pctDocs per 5 MB
full API tweet4,5955,86712,627893
trimmed (20 fields)9321,4613,8293,588

Trimming cut the mean document by 75.1%. For 1,000 tweets that is about 5.59 MB of request body untrimmed against 1.39 MB trimmed. The whole sample came to 9.14 MB full and 2.28 MB trimmed.

What that means for the helper settings. The Python client's streaming_bulk (which bulk wraps) flushes a chunk at chunk_size=500 actions or max_chunk_bytes of 100 MB, whichever comes first (signature of the 9.x client we installed). At the trimmed size, 500 documents is well under 1 MB per request, which is a reasonable starting point; at the full size, the 95th-percentile tweet is 12,627 bytes and the largest 31,644, so batches vary more. Elastic's own guidance is to experiment for your workload, and we did not benchmark throughput, so treat these as payload facts, not speed claims.

Keep the raw JSON elsewhere if you might need it. If a later question needs a field you dropped, re-reading tweets costs money and old search results can change. A cheap pattern is to write each raw page to object storage first and index the trimmed document; our Twitter API to S3 guide covers that half.

Horizontal bar chart of bulk NDJSON bytes per document: full API tweet median 4,595, mean 5,867, 95th percentile 12,627 bytes; trimmed 20-field document median 932, mean 1,461, 95th percentile 3,829 bytes. A 5 MB request holds about 893 full or 3,588 trimmed tweets.
Bytes per document in the bulk request body, full vs trimmed, over 1,633 posts collected in 2026.
05 — Section

The bulk loader in Python

The complete script is at the end of this page; this section explains the decisions in it. It uses requests for the X data (header X-API-Key, base https://api.twitterapi.io) and the official elasticsearch Python client (latest release 9.5.1 on PyPI, which requires Python 3.10 or newer).

Generator, not list. The Python client helpers docs recommend passing a generator to bulk() for large datasets so nothing has to sit in memory. The loader yields one action dict per tweet as pages arrive: {"_index": INDEX, "_id": tweet["id"], "_source": shape(tweet)}. Per those docs, _op_type defaults to index.

Read the errors. helpers.bulk() returns a tuple of the success count and a list of errors. By default it raises BulkIndexError on the first failed document; passing raise_on_error=False returns the failures instead, so one malformed document does not stop a back-fill. Print or log them: a mapping conflict shows up here and nowhere else.

Retries at both ends. On the X side, the loop retries a page after a 429 or 503 with a fixed 60-second wait and a cap of five attempts. On the Elasticsearch side, streaming_bulk already retries chunks rejected with 429 when you set max_retries (it defaults to 0), with exponential backoff starting at 2 seconds.

Pace the reads. Accounts start at 0.2 requests per second before the first payment and move to 20 once paid, so the loader keeps a fixed one-second pause between pages. A 50-page back-fill (about 1,000 tweets) spends 50 seconds in those pauses, plus the request time itself.

06 — Section

Three queries a tweet dashboard starts with

Once documents are in, the questions are usually the same three: how much is being posted over time, which tags travel with the topic, and in which languages. All three are one aggregation each, and they run together in a single size: 0 request.

Posts per hour. A date_histogram on created_at. Per the aggregation docs, fixed_interval takes SI units (ms, s, m, h, d) and never shifts with calendars, while calendar_interval follows daylight saving and month lengths; for hourly tweet volume fixed_interval: 1h is the predictable choice. The docs also note that buckets between the first and last matching document are returned, so quiet hours appear as zero buckets rather than gaps.

We computed the same 1-hour UTC buckets over the continuous recent part of the sample (980 posts across about 8.8 days). 26 of 213 buckets were empty, the median hour held 3 posts, the mean was 4.6, and the busiest hour held 28. A topic this size is a trickle with bursts, which is why a dashboard line chart with a 1-hour interval reads better than per-minute buckets.

Top hashtags. A terms aggregation on the lowercased hashtags keyword field. Only 17.1% of posts carried any hashtag (171 posts), which is a reminder that hashtag dashboards on a tech topic undercount the conversation; full-text match on text catches the rest. In the sample, counting only tags used by at least 5 distinct authors:

RankHashtag (lowercased)Posts
1openai33
2linux30
3ebpf27
4cybersecurity26
5shirudo24
6ai20
7opensearch17
8cisco15

Note how the list mixes the subject (opensearch, elasticsearch) with neighboring topics (ebpf, linux, cybersecurity). That is the normal output of a keyword search: the word appears in security, observability and AI posts. If you want only one sense, refine the query (for example add lang:en or exclude terms) before indexing rather than filtering in Kibana later. Our hashtag analytics guide goes deeper on tag-level metrics.

Language split. A terms aggregation on lang. X's language code is per post, and zxx marks posts with no detectable language (links or media only):

lang valuePostsShare
en49650.6%
zh18318.7%
ja14915.2%
zxx505.1%
es333.4%
pt131.3%

Half of the posts were not in English. If you plan full-text search across them, a single standard analyzer works passably for European languages but tokenizes Chinese and Japanese poorly; per-language sub-fields or a separate index per language are the usual fixes, and the lang keyword is what you route on.

json
GET /tweets-elasticsearch/_search
{
  "size": 0,
  "query": { "range": { "created_at": { "gte": "now-7d" } } },
  "aggs": {
    "per_hour":     { "date_histogram": { "field": "created_at", "fixed_interval": "1h" } },
    "top_hashtags": { "terms": { "field": "hashtags", "size": 10 } },
    "languages":    { "terms": { "field": "lang", "size": 8 } },
    "top_authors":  { "terms": { "field": "author.userName", "size": 10 },
                      "aggs": { "views": { "sum": { "field": "viewCount" } } } }
  }
}
Bar chart of posts per 1-hour bucket over 213 hours: a burst peaking at 28 posts early in the window, then mostly 1 to 10 posts per hour; 26 empty buckets; dashed mean line at 4.6 posts per hour.
A date_histogram computed over 980 real posts collected in 2026, 1-hour UTC buckets.
07 — Section

A Kibana dashboard in four panels

In Kibana, create a data view on tweets-* (or your index name) with created_at as the time field. Then build panels in Lens, which the Kibana docs describe as the visualization editor where you drag fields onto the workspace and it suggests a chart, picking an aggregation such as a date histogram or top values automatically.

Panel 1, volume. Drag created_at onto the workspace: Lens proposes a bar or line chart over a date histogram. Set the interval to one hour for a week-long view.

Panel 2, top hashtags. Drag hashtags and choose top values (the terms aggregation); show 10.

Panel 3, languages. Top values of lang as a donut or bar chart.

Panel 4, the posts themselves. A saved Discover search with text, author.userName, likeCount and viewCount columns, sorted by created_at. Add a query bar filter such as text:"vector search" and every panel on the dashboard narrows together.

If your team prefers a code-first dashboard instead of Kibana, the same documents can feed a Streamlit app or Grafana; the Elasticsearch queries above are what those tools would send.

08 — Section

Keeping the index current, and what it costs

Incremental runs. Ask the index for its newest created_at (a max aggregation), subtract a short overlap, and search with since_time:<unix> added to the query. Because _id is the tweet id, the overlap re-indexes a few documents rather than duplicating them. Schedule it with cron, a container job, or an Airflow task.

Pricing on the read side. TwitterAPI.io bills tweet endpoints at 15 credits per tweet returned, $0.15 per 1,000 tweets, with a 15-credit minimum per request, so a check that finds nothing costs $0.00015 and a full 20-tweet page $0.003. The official X API lists post reads at $0.005 each on its pay-per-usage plan (capped at 3 million post reads per monthly billing cycle; Enterprise above), which is $5 per 1,000, about 33x more per tweet.

JobTwitterAPI.ioOfficial X API (pay per use)
Back-fill 10,000 tweets$1.50$50
This study: 1,633 tweets$0.25about $8.17
Empty incremental check$0.00015 minimumbilled per post returned
Check every 60 s for a month, nothing new$6.48see docs.x.com pricing

The X API column uses $0.005 per post read from docs.x.com/x-api/getting-started/pricing. The polling figure is the floor: a check every 60 seconds for a month is 43,200 checks, $6.48 if every one returns nothing; every 5 minutes it is $1.30. New accounts get free starter credits (no card, one per person or network, expiring after 31 days) after an automatic bot check; see pricing for the current amount and plans.

Elasticsearch side. Self-managed Elasticsearch costs you the servers; Elastic Cloud is billed by Elastic. We do not quote Elastic prices here; check Elastic's own pricing page for your region.

python
import time

def newest_indexed(es, index):
    r = es.search(index=index, size=0, aggs={"newest": {"max": {"field": "created_at"}}})
    v = r["aggregations"]["newest"]["value"]          # epoch millis, or None on an empty index
    return int(v // 1000) if v else int(time.time()) - 3600

since = newest_indexed(es, INDEX) - 120               # overlap two minutes; _id makes repeats harmless
query = f"{QUERY} since_time:{since}"
ok, errors = helpers.bulk(es, actions(query, MAX_PAGES), raise_on_error=False)
09 — Section

How we collected this

Question. What does a real batch of tweets look like to an Elasticsearch index: date format, value ranges, optional-field presence, text length, keyword lengths, bulk payload size, and the three standard dashboard aggregations?

Query. (elasticsearch OR opensearch OR kibana) -filter:retweets on /twitter/tweet/advanced_search with queryType=Latest, paged by next_cursor, with older windows reached by stepping until_time back.

Sample and window. 1,633 posts from 83 requests, 0 duplicate ids across windows, collected in 2026. Reading them cost about $0.25. The stepped windows left a gap, so time aggregations use only the continuous recent window (980 posts, about 8.8 days).

Method. Python computed the aggregates with the same bucketing Elasticsearch uses (UTC hours, lowercase hashtag terms), and payload sizes are the exact byte length of the NDJSON lines the bulk helper would send. The 20-field trimmed document is the shape() function in the script below.

What the sample cannot show. No Elasticsearch cluster was available on the build machine, so on-disk index size, indexing throughput and query latency were not measured. One topic over about a week is not every topic: a sports or news keyword will have far higher hourly peaks and a different language mix.

Privacy. Aggregates only. Raw pages stayed in a temporary folder; the published sample holds de-identified numeric rows with no tweet ids, URLs, text, handles or author ids. Hashtags are reported as topic terms used by at least 5 distinct authors, never tied to a person.

python
"""Index X (Twitter) search results into Elasticsearch, then run three dashboard queries.
pip install requests "elasticsearch>=9" ; export TWITTERAPI_KEY=... ES_URL=... ES_API_KEY=..."""
import os
import time
from datetime import datetime, timezone

import requests
from elasticsearch import Elasticsearch, helpers

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_KEY"]}
INDEX = "tweets-elasticsearch"
QUERY = "(elasticsearch OR opensearch OR kibana) -filter:retweets"
MAX_PAGES = 50  # 20 tweets per page; 1,000 tweets cost $0.15

es = Elasticsearch(os.environ.get("ES_URL", "http://localhost:9200"),
                   api_key=os.environ.get("ES_API_KEY"))

MAPPING = {
    "dynamic": False,  # unknown fields stay in _source but are not indexed
    "properties": {
        "id": {"type": "keyword"},
        "url": {"type": "keyword", "index": False},
        "text": {"type": "text"},
        "lang": {"type": "keyword"},
        "created_at": {"type": "date"},
        "author": {"properties": {
            "id": {"type": "keyword"},
            "userName": {"type": "keyword"},
            "followers": {"type": "long"},
            "isBlueVerified": {"type": "boolean"},
        }},
        "likeCount": {"type": "integer"},
        "retweetCount": {"type": "integer"},
        "replyCount": {"type": "integer"},
        "quoteCount": {"type": "integer"},
        "bookmarkCount": {"type": "integer"},
        "viewCount": {"type": "long"},
        "isReply": {"type": "boolean"},
        "conversationId": {"type": "keyword"},
        "hashtags": {"type": "keyword"},
        "urls": {"type": "keyword", "ignore_above": 2048},
        "media_types": {"type": "keyword"},
        "is_quote": {"type": "boolean"},
    },
}

FMT = "%a %b %d %H:%M:%S %z %Y"  # createdAt looks like "Thu Oct 16 12:34:56 +0000 2025"


def shape(t):
    """Trim one API tweet to the fields the index maps (about a quarter of the raw bytes)."""
    a = t.get("author") or {}
    ent = t.get("entities") or {}
    media = (t.get("extendedEntities") or {}).get("media") or []
    created = datetime.strptime(t["createdAt"], FMT).astimezone(timezone.utc)
    return {
        "id": t["id"], "url": t.get("url"), "text": t.get("text"), "lang": t.get("lang"),
        "created_at": created.strftime("%Y-%m-%dT%H:%M:%SZ"),
        "author": {"id": a.get("id"), "userName": a.get("userName"),
                   "followers": a.get("followers"), "isBlueVerified": a.get("isBlueVerified")},
        "likeCount": t.get("likeCount"), "retweetCount": t.get("retweetCount"),
        "replyCount": t.get("replyCount"), "quoteCount": t.get("quoteCount"),
        "viewCount": t.get("viewCount"), "bookmarkCount": t.get("bookmarkCount"),
        "isReply": t.get("isReply"), "conversationId": t.get("conversationId"),
        "hashtags": [h.get("text", "").lower() for h in ent.get("hashtags") or []],
        "urls": [u["expanded_url"] for u in ent.get("urls") or [] if u.get("expanded_url")],
        "media_types": [m.get("type") for m in media],
        "is_quote": bool(t.get("quoted_tweet")),
    }


def fetch_tweets(query, max_pages):
    cursor, pages, retries = "", 0, 0
    while pages < max_pages:
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS,
                         params={"query": query, "queryType": "Latest", "cursor": cursor},
                         timeout=30)
        if r.status_code in (429, 503) and retries < 5:  # wait, then retry the same page
            retries += 1
            time.sleep(60)
            continue
        r.raise_for_status()
        retries, pages = 0, pages + 1
        body = r.json()
        yield from body.get("tweets") or []
        if not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor") or ""
        time.sleep(1)  # fixed pacing between pages


def actions(query, max_pages):
    for t in fetch_tweets(query, max_pages):
        # _op_type defaults to "index": re-running overwrites by _id, never duplicates
        yield {"_index": INDEX, "_id": t["id"], "_source": shape(t)}


if not es.indices.exists(index=INDEX):
    es.indices.create(index=INDEX, mappings=MAPPING)

ok, errors = helpers.bulk(es, actions(QUERY, MAX_PAGES), chunk_size=500, raise_on_error=False)
print(f"indexed {ok} documents, {len(errors)} errors")
for e in errors[:5]:
    print(e)
es.indices.refresh(index=INDEX)

# 1) full-text search, newest first
hits = es.search(index=INDEX, size=5, query={"match": {"text": "vector search"}},
                 sort=[{"created_at": "desc"}])
for h in hits["hits"]["hits"]:
    print(h["_source"]["created_at"], h["_source"]["text"][:80].replace("\n", " "))

# 2) posts per hour + 3) top hashtags + language split, in one request
aggs = es.search(index=INDEX, size=0, aggs={
    "per_hour": {"date_histogram": {"field": "created_at", "fixed_interval": "1h"}},
    "top_hashtags": {"terms": {"field": "hashtags", "size": 10}},
    "languages": {"terms": {"field": "lang", "size": 8}},
})["aggregations"]
print("busiest hour:", max(aggs["per_hour"]["buckets"], key=lambda b: b["doc_count"]))
print("hashtags:", [(b["key"], b["doc_count"]) for b in aggs["top_hashtags"]["buckets"]])
print("languages:", [(b["key"], b["doc_count"]) for b in aggs["languages"]["buckets"]])

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

How do I get tweets into Elasticsearch without Logstash?

Use a short Python script: page through /twitter/tweet/advanced_search with next_cursor, shape each tweet into a document, and send them with elasticsearch.helpers.bulk() using the tweet id as _id. The Logstash Twitter input and the old Twitter river relied on X streaming access that is no longer available in that form; an HTTPS polling loop has no such dependency.

What mapping should I use for tweets in Elasticsearch?

Declare it explicitly: text as text, created_at as date, like, retweet, reply, quote and bookmark counts as integer, viewCount and follower counts as long, and hashtags, lang, urls and author.userName as keyword. In our 1,633-post sample, 59.6% of texts were longer than 256 characters, so a keyword text field would lose them.

Why does Elasticsearch map the tweet date as text?

Because createdAt comes as Thu Oct 16 12:34:56 +0000 2025, which matches neither default dynamic date format (strict_date_optional_time and yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z). Convert it to ISO 8601 in Python with %a %b %d %H:%M:%S %z %Y before indexing, or declare a date field with a custom format.

How many tweets should one bulk request hold?

Elastic says there is no correct number and recommends testing. As a payload fact, a trimmed tweet averaged 1,461 bytes of NDJSON in our sample, so the Python helper's default chunk of 500 actions is well under 1 MB; full API tweets averaged 5,867 bytes. The server caps a request at 100 MB by default.

How do I avoid duplicate tweets in the index?

Set _id to the tweet id and keep the default index action. A second write with the same id replaces the document (and refreshes its counts) instead of adding a copy. The create action would fail on the duplicate instead.

Can I build a Twitter Kibana dashboard from this index?

Yes. Create a data view on the index with created_at as the time field, then use Lens for a date histogram of volume, top values of hashtags and lang, and a saved Discover search of the posts. The query bar filters every panel at once.

How much does it cost to index 10,000 tweets?

On TwitterAPI.io, reading 10,000 tweets costs $1.50 ($0.15 per 1,000). On the official X API's pay-per-usage plan, post reads are $0.005 each, so $50. Elasticsearch hosting is separate. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); the amount is on the pricing page.

Does this work with OpenSearch?

The documents, the NDJSON bulk format and the date_histogram and terms aggregations are shared, but OpenSearch has its own Python client (opensearch-py) and dashboards. We verified only the Elasticsearch client and docs for this page, so check OpenSearch's docs for client differences.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.