Twitter (X) API to Neo4j: model, import and query a real follower and mention graph

By TwitterAPI.io Team•16 min read
Neo4j graph model for Twitter (X) data: User, Tweet and Hashtag nodes joined by POSTED, MENTIONS, REPLIES_TO, RETWEETS, QUOTES, TAGS and FOLLOWS, with counts from a 12-organization import
The property-graph model used in this guide, with the node and relationship counts our 12-organization import produced (collected in 2026).
TL;DR
  • Model: :User, :Tweet, :Hashtag nodes; POSTED, MENTIONS, REPLIES_TO, QUOTES, RETWEETS, TAGS, FOLLOWS relationships, each node keyed on the X id (or lowercased tag).
  • Real run: 12 organization accounts, 946 posts + 2,103 following records became 3,395 nodes and 4,086 relationships (collected in 2026).
  • MERGE matters: 3,841 User rows collapsed into 2,174 User nodes; 20.4% of all 9,404 MERGE rows matched an existing node or relationship.
  • Follow lists barely overlap: 93.5% of the 1,929 accounts the seeds follow are followed by only one seed; LangChain is followed by 6 of 12.
  • PageRank needs the right subgraph: on the full sample it is flat (top score 0.0005 vs a uniform 0.00046); on the 18 seed-to-seed follows confluentinc leads with 0.1821.
  • Cost: the reads behind this graph cost under $0.21 at $0.15 per 1,000 tweets; on the official X API rate card they come to $25.76.

This is the database build, not the theory. Our Twitter network analysis guide covers the concepts (nodes, edges, centrality, communities) in Python with networkx and Gephi; this page puts the same kind of data into Neo4j, where it persists, grows run after run, and is queried with Cypher instead of being rebuilt in memory every time.

Graph databases fit X data unusually well because the interesting questions are about relationships: who follows whom back, which accounts a group of brands all follow, which posts sit at the root of a long reply chain, who gets mentioned by whom. In a relational database each of those is a stack of self-joins; in Neo4j each is one MATCH pattern. The catch is the import: X data repeats the same accounts and posts across pages, so a naive CREATE duplicates them. Everything below is built around idempotent MERGE.

To keep it honest, we ran the whole model on real data: the latest posts and first page of followings for 12 public data-infrastructure organization accounts (neo4j, MongoDB, Redisinc, elastic, supabase, databricks, Snowflake, confluentinc, github, Docker, vercel, awscloud). The counts, the co-follow table and the PageRank results on this page come from that run.

Real import: 12 organization accounts, collected in 2026

3,395 nodes and 4,086 relationships from 9,404 MERGE rows (20.4% absorbed as duplicates)

01 — Section

The graph model: three labels, seven relationship types

Neo4j stores a property graph: nodes carry labels and properties, relationships carry a type, a direction and optional properties. For X data, a small model covers nearly every question people ask. Keep it small; you can add labels later without migrating anything.

ElementKey (MERGE on this)Useful propertiesComes from
:Userid (X user id, string)userName, followersauthor, entities.user_mentions, followings
:Tweetid (X post id, string)text, createdAt, likes, viewsevery post, plus reply / quote / repost targets
:Hashtagname (lowercased)none neededentities.hashtags

Relationships. (:User)-[:POSTED]->(:Tweet) links an author to a post. (:Tweet)-[:MENTIONS]->(:User) comes from entities.user_mentions. (:Tweet)-[:REPLIES_TO]->(:Tweet) uses inReplyToId, (:Tweet)-[:QUOTES]->(:Tweet) uses quoted_tweet.id, and (:Tweet)-[:RETWEETS]->(:Tweet) uses retweeted_tweet.id. (:Tweet)-[:TAGS]->(:Hashtag) comes from entities.hashtags, and (:User)-[:FOLLOWS]->(:User) comes from a follower or following list.

Key on the id, never the handle. Handles change; the numeric X id does not. Store ids as strings: they exceed the range JavaScript clients handle safely, and the API already returns them as strings. Keep userName as a property you overwrite with SET on every import, so a renamed account updates in place.

Mentions point at users, replies point at posts. It is tempting to draw (:User)-[:REPLIED_TO]->(:User), but replies form trees of posts, and you lose the tree if you collapse them to users. Store the post-to-post edge; derive user-to-user views in a query when you need them.

A :Seed label for the accounts you collected. Accounts you pulled timelines and follow lists for are complete in a way that mentioned accounts are not. Marking them with an extra label (SET s:Seed) keeps queries honest: a co-follow count only means something among accounts whose follow lists you actually loaded.

02 — Section

Step 1: collect posts and follow lists from the API

Two read endpoints feed this model. /twitter/user/last_tweets with userName returns an account's latest posts, 20 per page, newest first, under data.tweets[], with has_next_page and next_cursor for paging; includeReplies=true adds the account's replies, which you want, because replies are where the REPLIES_TO and MENTIONS edges come from. /twitter/user/followings with userName and pageSize=200 returns up to 200 followed accounts per page under top-level followings[] in snake_case (id, screen_name, followers_count, ...). For followers rather than followings, /twitter/user/followers has the same shape; our guide to exporting an account's followers covers paging through large lists.

Fields the import reads. On each post: id, text, createdAt (format Thu Oct 16 12:34:56 +0000 2026, which you convert to ISO 8601 before Cypher's datetime() can parse it), likeCount, viewCount, isReply, inReplyToId, author.id, author.userName, author.followers, entities.user_mentions[].id_str and .screen_name, entities.hashtags[].text, quoted_tweet.id and retweeted_tweet.id. Every one of these is read exactly as the API returns it; there is no public_metrics object.

What it costs. Reads are billed per item returned: $0.15 per 1,000 tweets (15 credits per tweet) and 1 to 3 credits per user on follower and following lists, with a 15-credit minimum per request, so an empty page costs $0.00015. No X account is needed for reads. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the amount.

Pacing. Before the first payment the rate limit is 0.2 requests per second; once paid it is 20 requests per second (50 on Scale, 500 on Business). The example below waits a fixed 0.25 seconds between pages and a fixed 60 seconds on a 429 or 503, which keeps a three-account import well inside either limit.

python
import os
import time
from datetime import datetime

import requests
from neo4j import GraphDatabase

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
NEO4J_URI = os.environ.get("NEO4J_URI", "neo4j://localhost:7687")
NEO4J_AUTH = (os.environ.get("NEO4J_USER", "neo4j"), os.environ["NEO4J_PASSWORD"])
SEEDS = ["neo4j", "MongoDB", "confluentinc"]   # public organization accounts


def get(url, params):
    """GET with a fixed pause between pages and a fixed back-off on 429 / 503."""
    for _ in range(5):
        r = requests.get(url, headers=HEADERS, params=params, timeout=30)
        if r.status_code in (429, 503):
            time.sleep(60)
            continue
        r.raise_for_status()
        time.sleep(0.25)
        return r.json()
    raise RuntimeError(f"gave up on {url}")


def last_tweets(user, pages=4):
    out, cursor = [], ""
    for _ in range(pages):
        body = get(f"{BASE}/twitter/user/last_tweets",
                   {"userName": user, "includeReplies": "true", "cursor": cursor})
        out += (body.get("data") or {}).get("tweets", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return out


def followings(user, pages=1):
    out, cursor = [], ""
    for _ in range(pages):
        body = get(f"{BASE}/twitter/user/followings",
                   {"userName": user, "pageSize": 200, "cursor": cursor})
        out += body.get("followings", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return out


def tweet_row(t):
    """Flatten one tweet into the row shape the Cypher below expects."""
    a, ent = t["author"], t.get("entities") or {}
    rt, qt = t.get("retweeted_tweet") or {}, t.get("quoted_tweet") or {}
    created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    return {
        "id": t["id"], "text": t.get("text", ""), "created": created.isoformat(),
        "likes": t.get("likeCount", 0), "views": t.get("viewCount") or 0,
        "author": {"id": a["id"], "userName": a["userName"], "followers": a.get("followers", 0)},
        "mentions": [{"id": m["id_str"], "userName": m.get("screen_name")}
                     for m in ent.get("user_mentions") or []],
        "hashtags": sorted({h["text"].lower() for h in ent.get("hashtags") or []}),
        "reply_to": t.get("inReplyToId") if t.get("isReply") else None,
        "quotes": qt.get("id"), "retweets": rt.get("id"),
    }
03 — Section

Step 2: constraints first, then an idempotent MERGE import

The Cypher manual is explicit on ordering: "It is recommended to create constraints prior to merging data." A uniqueness constraint creates the backing index that makes each MERGE a fast lookup instead of a label scan, and it stops two concurrent loaders from creating the same node twice. Per the constraints documentation, property uniqueness constraints are available in every edition; node key, existence and type constraints are Enterprise Edition features, so the uniqueness form below works on Community, Desktop and Aura alike.

Batch with UNWIND $rows. Send a list of flattened rows as one parameter and let Cypher iterate, instead of one round trip per post. Batches of a few hundred rows keep each transaction small. Parameters ($rows) also let the server reuse the query plan; never build Cypher by string-concatenating post text.

MERGE on the key only, then SET the rest. Per the MERGE documentation, MERGE matches or creates the whole pattern you give it, so MERGE (u:User {id: $id, userName: $name}) would create a second node the day the account renames itself. Merge on id, then SET u.userName = .... Use ON CREATE SET for properties you only want to write once, such as the handle of a mentioned account that you have no profile for.

Nulls break MERGE. The same page notes that MERGE cannot be used with null property values: it raises an error. A post that is not a reply has no inReplyToId, so the reply, quote and repost edges are wrapped in FOREACH (x IN CASE WHEN ... IS NULL THEN [] ELSE [...] END | ...), which runs the inner MERGE zero or one time.

Placeholder nodes are fine. A reply's parent post or a quoted post may never be imported in full. MERGE (p:Tweet {id: pid}) creates a node holding just the id; if a later run imports that post, its MERGE matches the placeholder and SET fills in the text. That is how a graph grows correctly across runs.

python
SCHEMA = [
    "CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE",
    "CREATE CONSTRAINT tweet_id IF NOT EXISTS FOR (t:Tweet) REQUIRE t.id IS UNIQUE",
    "CREATE CONSTRAINT hashtag_name IF NOT EXISTS FOR (h:Hashtag) REQUIRE h.name IS UNIQUE",
]

IMPORT_TWEETS = """
UNWIND $rows AS row
MERGE (u:User {id: row.author.id})
  SET u.userName = row.author.userName, u.followers = row.author.followers
MERGE (t:Tweet {id: row.id})
  SET t.text = row.text, t.createdAt = datetime(row.created),
      t.likes = row.likes, t.views = row.views
MERGE (u)-[:POSTED]->(t)
FOREACH (m IN row.mentions |
  MERGE (mu:User {id: m.id}) ON CREATE SET mu.userName = m.userName
  MERGE (t)-[:MENTIONS]->(mu))
FOREACH (tag IN row.hashtags |
  MERGE (h:Hashtag {name: tag})
  MERGE (t)-[:TAGS]->(h))
FOREACH (pid IN CASE WHEN row.reply_to IS NULL THEN [] ELSE [row.reply_to] END |
  MERGE (p:Tweet {id: pid})
  MERGE (t)-[:REPLIES_TO]->(p))
FOREACH (qid IN CASE WHEN row.quotes IS NULL THEN [] ELSE [row.quotes] END |
  MERGE (q:Tweet {id: qid})
  MERGE (t)-[:QUOTES]->(q))
FOREACH (rid IN CASE WHEN row.retweets IS NULL THEN [] ELSE [row.retweets] END |
  MERGE (o:Tweet {id: rid})
  MERGE (t)-[:RETWEETS]->(o))
"""

IMPORT_FOLLOWS = """
MATCH (s:User {id: $seed_id})
SET s:Seed
WITH s
UNWIND $rows AS row
MERGE (u:User {id: row.id})
  ON CREATE SET u.userName = row.screen_name, u.followers = row.followers_count
MERGE (s)-[:FOLLOWS]->(u)
"""


def batches(rows, size=500):
    for i in range(0, len(rows), size):
        yield rows[i:i + size]


with GraphDatabase.driver(NEO4J_URI, auth=NEO4J_AUTH) as driver:
    for stmt in SCHEMA:
        driver.execute_query(stmt)
    for seed in SEEDS:
        tweets = last_tweets(seed)
        if not tweets:
            print(seed, "no posts returned, check the handle")
            continue
        rows = [tweet_row(t) for t in tweets]
        for chunk in batches(rows):
            driver.execute_query(IMPORT_TWEETS, rows=chunk)
        seed_id = tweets[0]["author"]["id"]
        frows = [{"id": f["id"], "screen_name": f.get("screen_name"),
                  "followers_count": f.get("followers_count", 0)} for f in followings(seed)]
        for chunk in batches(frows):
            driver.execute_query(IMPORT_FOLLOWS, seed_id=seed_id, rows=chunk)
        print(seed, len(rows), "posts,", len(frows), "followings")

    records, summary, keys = driver.execute_query("""
        MATCH (a:Seed)-[:FOLLOWS]->(b:Seed)-[:FOLLOWS]->(a)
        WHERE a.id < b.id
        RETURN a.userName AS a, b.userName AS b
    """)
    for r in records:
        print("mutual follow:", r["a"], "<->", r["b"])
04 — Section

What the import produced: real counts from 12 organization accounts

We ran this model over the 12 seed organizations: up to 4 pages of posts each (replies included) and the first page of each account's followings. That gave 946 posts and 2,103 following records. Because we had no Neo4j server for this study, we built the graph in Python with the exact node keys and relationship rules of the Cypher above, so the counts equal what the import would store; the Cypher itself is written per the Neo4j docs and was not executed against a database.

Label or typeMERGE rows sentStoredAbsorbed by MERGE
:User3,8412,1741,667
:Tweet1,2961,180116
:Hashtag1374196
POSTED1,0981,08711
MENTIONS44241428
REPLIES_TO1981962
RETWEETS1271270
QUOTES25250
TAGS1371343
FOLLOWS2,1032,1030
Total9,4047,4811,923

Users are where duplicates pile up. 3,841 User rows collapsed into 2,174 User nodes, because the same accounts appear as authors on every post, as mention targets, and in several seeds' follow lists. Tweets dedupe less (1,296 rows to 1,180 nodes), because reply, quote and repost targets are sometimes posts already in the sample. Across every label and type, 20.4% of the 9,404 MERGE rows matched something that already existed. With CREATE instead of MERGE, every one of those would be a duplicate node or edge.

Followings dominate the edge count. FOLLOWS is 2,103 of 4,086 relationships, more than half, from just one page per account. A graph that loads full follower lists of large accounts becomes a follow graph with some posts attached; plan memory and batch sizes around the follow lists, not the posts.

The hashtag layer is thin. These organizations used only 41 distinct hashtags across 134 tags. For brand accounts, MENTIONS (414 distinct post-to-user edges) carries far more structure than hashtags do.

Bar chart comparing MERGE rows sent with distinct nodes and relationships stored for each label and type; 3,841 User rows become 2,174 User nodes
MERGE rows sent vs nodes and relationships stored, per label and type. 12 organization accounts, 946 posts and 2,103 following records, collected in 2026.
05 — Section

Step 3: Cypher for mutual follows, co-follows, mentions and reply chains, and what it returns

With the graph loaded, each question that would be a multi-way self-join in SQL is a single pattern. The queries below use only core Cypher (no plugins) and run on any Neo4j edition, including the free Aura tier and Desktop.

Mutual follows match a two-hop pattern back to the start node; a.id < b.id keeps each pair once instead of twice. Co-follows count how many seeds point at the same account, a simple and robust signal of who matters to a group. Mention hubs aggregate MENTIONS edges from the seeds' posts. Reply depth uses a variable-length pattern [:REPLIES_TO*1..10]; always cap the length, because an uncapped variable-length match on a large graph can explore an enormous number of paths.

Cap reply-chain depth for a second reason: our data shows how shallow organization threads are. For an account's own replies, the parent is usually a post by someone else, and your graph only holds the full chain if you also import the conversation (see the thread section below).

Mutual follows are rare among brands. Among the 12 seeds there are 18 seed-to-seed follow edges and only 4 mutual pairs: MongoDB and confluentinc, Snowflake and confluentinc, awscloud and elastic, confluentinc and elastic. No other seed follows neo4j, Redisinc or supabase in the loaded lists, and neo4j and supabase follow no other seed either. (vercel follows only 10 accounts in total supabase 107 and elastic 186, so those three lists are complete; for the other seeds we loaded the first page only.)

Co-follows surface the shared ecosystem. Of the 1,929 distinct accounts the seeds follow, 1,803 (93.5%) are followed by exactly one seed, 96 by two and 30 by three or more. The accounts followed by three or more seeds are AI labs, cloud platforms and developer media, the shared reference points of the data-infrastructure world. 12 of the 30 are individual people (founders, analysts, journalists); we list only organizations.

AccountFollowed by (of 12 seeds)Kind
LangChain6organization
DeepLearningAI5organization
msPartner4organization
theCUBE4organization
huggingface4organization
googlecloud4organization
gcloudpartners4organization
confluentinc4seed organization
Azure4organization
AnthropicAI4organization

Posting style changes the graph shape. How much each seed contributes to the REPLIES_TO, RETWEETS and MENTIONS layers depends on how it uses X. An account that replies a lot to customers adds many REPLIES_TO edges and mentions; one that reposts adds RETWEETS edges and few mentions of its own.

Seed accountPostsRepliesRepostsDistinct accounts mentioned
neo4j805.0%22.5%7
MongoDB7540.0%0.0%77
Redisinc7917.7%13.9%8
elastic8139.5%2.5%8
supabase8010.0%60.0%10
databricks801.3%26.3%27
Snowflake8116.0%1.2%37
confluentinc7512.0%8.0%27
github7917.7%20.3%14
Docker789.0%1.3%32
vercel7816.7%2.6%21
awscloud8066.2%1.3%42

Reading the table. awscloud is a support-desk timeline (66.2% replies) and MongoDB mentions 77 distinct accounts in 75 posts, while supabase is 60% reposts. If you build a mention graph from timelines like these, reply-heavy brands dominate it; normalize by post count before comparing accounts.

cypher
// 1. Mutual follows between seed organizations
MATCH (a:Seed)-[:FOLLOWS]->(b:Seed)-[:FOLLOWS]->(a)
WHERE a.id < b.id
RETURN a.userName AS a, b.userName AS b;

// 2. Accounts followed by several seeds (co-follow ranking)
MATCH (s:Seed)-[:FOLLOWS]->(u:User)
RETURN u.userName AS account, count(s) AS seeds
ORDER BY seeds DESC, account
LIMIT 20;

// 3. Mention hubs: who the seeds' posts mention, and how often
MATCH (:Seed)-[:POSTED]->(t:Tweet)-[:MENTIONS]->(u:User)
RETURN u.userName AS account, count(t) AS mentions
ORDER BY mentions DESC
LIMIT 20;

// 4. Reply chains: walk REPLIES_TO up to the root post
MATCH path = (leaf:Tweet)-[:REPLIES_TO*1..10]->(root:Tweet)
WHERE NOT (root)-[:REPLIES_TO]->() AND NOT ()-[:REPLIES_TO]->(leaf)
RETURN root.id AS root, length(path) AS depth
ORDER BY depth DESC
LIMIT 10;

// 5. Hashtags two seeds share
MATCH (a:Seed)-[:POSTED]->(:Tweet)-[:TAGS]->(h:Hashtag)<-[:TAGS]-(:Tweet)<-[:POSTED]-(b:Seed)
WHERE a.id < b.id
RETURN h.name AS hashtag, collect(DISTINCT a.userName + " & " + b.userName) AS pairs;
06 — Section

Step 4: PageRank with the Graph Data Science library

Neo4j's Graph Data Science (GDS) library runs graph algorithms on an in-memory projection of your stored graph. Per the GDS installation docs, it is available as a plugin for self-managed Neo4j (Community or Enterprise server), from the Neo4j Desktop UI, fully managed in AuraDS, and through Aura Graph Analytics; the Enterprise Edition of GDS needs a license key.

The pattern is two steps: project, then run. The Cypher projection gds.graph.project(name, source, target) takes the matched pairs and builds the in-memory graph; gds.pageRank.stream(name) returns a nodeId and score per node, and gds.util.asNode(nodeId) turns the id back into the stored node. Per the PageRank docs, the defaults are a damping factor of 0.85 and 20 iterations. Drop a projection with gds.graph.drop when you are done; it holds memory until you do.

What we found when we ran PageRank on this sample (with networkx, same definition and damping factor): on the full 2,174-node user graph the scores are nearly flat. The top score is 0.0005 against a uniform baseline of 0.00046, and 11 of the top 25 nodes have exactly one incoming edge. That is not a bug: a sample built from 12 follow lists is 12 stars, and almost every leaf has one follower in your data. PageRank only says something when the graph has many paths between nodes.

Project the subgraph you trust. Restricting the projection to :Seed accounts gives a small graph with complete edges between known nodes, and there the ranking is clear:

SeedPageRank (seed graph)Followed by other seeds
confluentinc0.1824
elastic0.1512
Docker0.1073
databricks0.1053
awscloud0.0992
github0.0681

confluentinc is followed by 4 of the other 11 seeds and sits in 3 of the 4 mutual pairs, so it ranks first; seeds no other seed follows all share the floor score of 0.036. For a larger PageRank study, collect the follow lists of the accounts your seeds follow (a second hop) before projecting, or use co-follow counts, which already work on a one-hop sample.

cypher
// Project the FOLLOWS graph into the GDS catalog (Cypher projection)
MATCH (source:User)-[:FOLLOWS]->(target:User)
RETURN gds.graph.project('follows', source, target);

// Stream PageRank (defaults per the GDS docs: dampingFactor 0.85, maxIterations 20)
CALL gds.pageRank.stream('follows')
YIELD nodeId, score
RETURN gds.util.asNode(nodeId).userName AS account, score
ORDER BY score DESC
LIMIT 10;

// Same ranking restricted to seed-to-seed follows
MATCH (source:Seed)-[:FOLLOWS]->(target:Seed)
RETURN gds.graph.project('seedFollows', source, target);

CALL gds.pageRank.stream('seedFollows')
YIELD nodeId, score
RETURN gds.util.asNode(nodeId).userName AS account, round(score, 3) AS score
ORDER BY score DESC;
Left: organizations followed by three or more of the 12 seed accounts, led by LangChain with 6. Right: PageRank within the 12-seed follow graph, led by confluentinc
Co-followed organizations (left) and PageRank inside the seed-to-seed follow graph (right). 12 organization accounts, collected in 2026.
07 — Section

Reply trees and knowledge graphs: extending the model

A post's REPLIES_TO edge points at its parent, but a timeline only gives you the replies one account wrote. To rebuild a whole thread, pull every post in the conversation with /twitter/tweet/advanced_search and the query conversation_id:<id> (each post carries its conversationId), then feed those posts through the same IMPORT_TWEETS statement. The placeholder parent nodes created earlier get filled in, and [:REPLIES_TO*] paths now reach the root. Our conversation_id guide explains how the id behaves.

From a social graph to a knowledge graph. "Twitter knowledge graph" usually means adding entity nodes next to the social layer: (:Tweet)-[:LINKS_TO]->(:Domain) from entities.urls[].expanded_url, (:Tweet)-[:ABOUT]->(:Topic) from an entity extractor or topic model, (:User)-[:WORKS_AT]->(:Organization) from bios. The import pattern is the same: flatten to rows, MERGE on a stable key, SET the rest. Keep the extraction step (NLP, an LLM, regex on URLs) outside the database and store its output with a property that names the model or rule, so you can re-run it later.

Neo4j alongside a relational store. Many teams keep raw posts in a relational database or object storage and load only the relationships into Neo4j. If that is your setup, our PostgreSQL pipeline guide covers the storage side; the graph then holds ids, a few properties for display, and the edges.

Keeping it current. Re-running the import on a schedule is safe because every statement is a MERGE. Follower lists change slowly, so refresh them less often than posts. To record unfollows, stamp each FOLLOWS edge with r.seenAt = datetime() on every run and delete edges whose seenAt is older than the latest refresh of that seed.

python
import os
import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}


def conversation(conversation_id, max_pages=5):
    """Every public reply in one thread, ready for the same IMPORT_TWEETS Cypher."""
    tweets, cursor = [], ""
    for _ in range(max_pages):
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS, timeout=30,
                         params={"query": f"conversation_id:{conversation_id}",
                                 "queryType": "Latest", "cursor": cursor})
        r.raise_for_status()
        body = r.json()
        tweets += body.get("tweets", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return tweets
08 — Section

Cost of building the graph vs the official X API

Graph builds are read-heavy and follow-list-heavy, which is exactly where per-item pricing differences add up. On the official X API pay-per-usage rate card (docs.x.com, pricing page), a post read costs $0.005, a user read $0.010 and each follower or following record $0.010; pay-per-usage is capped at 3 million post reads per monthly billing cycle, with Enterprise above that. TwitterAPI.io bills $0.15 per 1,000 tweets returned and 1 to 3 credits per follower or following record, with no X developer account.

What the study pulledVolumeTwitterAPI.ioOfficial X API (pay-per-usage)
Posts (timelines)946$0.14 ($0.15 per 1,000)$4.73 ($0.005 each)
Following records2,103$0.02 to $0.06 (1 to 3 credits each)$21.03 ($0.010 each)
Totalunder $0.21$25.76

Per 1,000 posts that is $5.00 on the official rate card against $0.15, about 33 times more. The bigger gap here is follow lists: at $0.010 per record, a single 10,000-follower list costs $100 on the official API. Subscriptions (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499 a month) add bonus credits; see pricing for what each includes.

Budget the second hop. If you expand from 12 seeds to the follow lists of the accounts they follow, the volume jumps by two orders of magnitude. Sample first: load one page of each second-hop list, check that co-follow counts stabilize, then decide whether full lists are worth it.

09 — Section

How we collected this

Question. What does real X data look like once it is modeled the Neo4j way: how many nodes and relationships per label and type, how many MERGE rows an idempotent import writes, which seed organizations follow each other, how concentrated their follow lists are, and what PageRank returns.

Accounts. 12 public organization accounts in data infrastructure and developer platforms: neo4j, MongoDB, Redisinc, elastic, supabase, databricks, Snowflake, confluentinc, github, Docker, vercel, awscloud.

Method and sample. For each account, up to 4 pages of /twitter/user/last_tweets with replies included (946 posts in total) and the first page of /twitter/user/followings with pageSize=200 (2,103 records). 64 API requests, collected in 2026. The graph was built in Python with networkx using the same keys and rules as the Cypher on this page; PageRank used a damping factor of 0.85. No Neo4j server was run, so the Cypher is shown per the Neo4j documentation, not as executed output.

Window. The latest posts of each account at collection time; the window differs per account depending on how often it posts.

What the sample cannot show. Follow lists beyond the first page (only the vercel, supabase and elastic lists are complete), the follower side of each account, second-hop structure, and any Neo4j-specific timing (import speed, memory). Co-follow counts and seed-graph PageRank are only as complete as those first pages.

Privacy. Only organization accounts are named. Accounts that appear as mention targets, reply targets or followings are counted in aggregate; individuals are never named or profiled. Raw following pages stayed out of the published study files; the published sample is de-identified.

python
import os
import time
from datetime import datetime

import requests
from neo4j import GraphDatabase

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
NEO4J_URI = os.environ.get("NEO4J_URI", "neo4j://localhost:7687")
NEO4J_AUTH = (os.environ.get("NEO4J_USER", "neo4j"), os.environ["NEO4J_PASSWORD"])
SEEDS = ["neo4j", "MongoDB", "confluentinc"]   # public organization accounts


def get(url, params):
    """GET with a fixed pause between pages and a fixed back-off on 429 / 503."""
    for _ in range(5):
        r = requests.get(url, headers=HEADERS, params=params, timeout=30)
        if r.status_code in (429, 503):
            time.sleep(60)
            continue
        r.raise_for_status()
        time.sleep(0.25)
        return r.json()
    raise RuntimeError(f"gave up on {url}")


def last_tweets(user, pages=4):
    out, cursor = [], ""
    for _ in range(pages):
        body = get(f"{BASE}/twitter/user/last_tweets",
                   {"userName": user, "includeReplies": "true", "cursor": cursor})
        out += (body.get("data") or {}).get("tweets", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return out


def followings(user, pages=1):
    out, cursor = [], ""
    for _ in range(pages):
        body = get(f"{BASE}/twitter/user/followings",
                   {"userName": user, "pageSize": 200, "cursor": cursor})
        out += body.get("followings", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return out


def tweet_row(t):
    """Flatten one tweet into the row shape the Cypher below expects."""
    a, ent = t["author"], t.get("entities") or {}
    rt, qt = t.get("retweeted_tweet") or {}, t.get("quoted_tweet") or {}
    created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    return {
        "id": t["id"], "text": t.get("text", ""), "created": created.isoformat(),
        "likes": t.get("likeCount", 0), "views": t.get("viewCount") or 0,
        "author": {"id": a["id"], "userName": a["userName"], "followers": a.get("followers", 0)},
        "mentions": [{"id": m["id_str"], "userName": m.get("screen_name")}
                     for m in ent.get("user_mentions") or []],
        "hashtags": sorted({h["text"].lower() for h in ent.get("hashtags") or []}),
        "reply_to": t.get("inReplyToId") if t.get("isReply") else None,
        "quotes": qt.get("id"), "retweets": rt.get("id"),
    }


SCHEMA = [
    "CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE",
    "CREATE CONSTRAINT tweet_id IF NOT EXISTS FOR (t:Tweet) REQUIRE t.id IS UNIQUE",
    "CREATE CONSTRAINT hashtag_name IF NOT EXISTS FOR (h:Hashtag) REQUIRE h.name IS UNIQUE",
]

IMPORT_TWEETS = """
UNWIND $rows AS row
MERGE (u:User {id: row.author.id})
  SET u.userName = row.author.userName, u.followers = row.author.followers
MERGE (t:Tweet {id: row.id})
  SET t.text = row.text, t.createdAt = datetime(row.created),
      t.likes = row.likes, t.views = row.views
MERGE (u)-[:POSTED]->(t)
FOREACH (m IN row.mentions |
  MERGE (mu:User {id: m.id}) ON CREATE SET mu.userName = m.userName
  MERGE (t)-[:MENTIONS]->(mu))
FOREACH (tag IN row.hashtags |
  MERGE (h:Hashtag {name: tag})
  MERGE (t)-[:TAGS]->(h))
FOREACH (pid IN CASE WHEN row.reply_to IS NULL THEN [] ELSE [row.reply_to] END |
  MERGE (p:Tweet {id: pid})
  MERGE (t)-[:REPLIES_TO]->(p))
FOREACH (qid IN CASE WHEN row.quotes IS NULL THEN [] ELSE [row.quotes] END |
  MERGE (q:Tweet {id: qid})
  MERGE (t)-[:QUOTES]->(q))
FOREACH (rid IN CASE WHEN row.retweets IS NULL THEN [] ELSE [row.retweets] END |
  MERGE (o:Tweet {id: rid})
  MERGE (t)-[:RETWEETS]->(o))
"""

IMPORT_FOLLOWS = """
MATCH (s:User {id: $seed_id})
SET s:Seed
WITH s
UNWIND $rows AS row
MERGE (u:User {id: row.id})
  ON CREATE SET u.userName = row.screen_name, u.followers = row.followers_count
MERGE (s)-[:FOLLOWS]->(u)
"""


def batches(rows, size=500):
    for i in range(0, len(rows), size):
        yield rows[i:i + size]


with GraphDatabase.driver(NEO4J_URI, auth=NEO4J_AUTH) as driver:
    for stmt in SCHEMA:
        driver.execute_query(stmt)
    for seed in SEEDS:
        tweets = last_tweets(seed)
        if not tweets:
            print(seed, "no posts returned, check the handle")
            continue
        rows = [tweet_row(t) for t in tweets]
        for chunk in batches(rows):
            driver.execute_query(IMPORT_TWEETS, rows=chunk)
        seed_id = tweets[0]["author"]["id"]
        frows = [{"id": f["id"], "screen_name": f.get("screen_name"),
                  "followers_count": f.get("followers_count", 0)} for f in followings(seed)]
        for chunk in batches(frows):
            driver.execute_query(IMPORT_FOLLOWS, seed_id=seed_id, rows=chunk)
        print(seed, len(rows), "posts,", len(frows), "followings")

    records, summary, keys = driver.execute_query("""
        MATCH (a:Seed)-[:FOLLOWS]->(b:Seed)-[:FOLLOWS]->(a)
        WHERE a.id < b.id
        RETURN a.userName AS a, b.userName AS b
    """)
    for r in records:
        print("mutual follow:", r["a"], "<->", r["b"])

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 import Twitter (X) data into Neo4j?

Fetch posts and follow lists from an X data API, flatten each post into a row (id, text, author, mentions, hashtags, reply / quote / repost ids), create uniqueness constraints on User.id, Tweet.id and Hashtag.name, then send the rows in batches to a Cypher statement that starts with UNWIND $rows AS row and uses MERGE on the ids. The Python driver's execute_query runs each batch. Re-running the import is safe because MERGE matches existing nodes.

What is a good Neo4j data model for Twitter?

Three labels (User, Tweet, Hashtag) and seven relationship types: POSTED (User to Tweet), MENTIONS (Tweet to User), REPLIES_TO, QUOTES and RETWEETS (Tweet to Tweet), TAGS (Tweet to Hashtag) and FOLLOWS (User to User). Key users and posts on the X id, not the handle, and keep reply edges between posts so reply trees survive.

Why use MERGE instead of CREATE for tweets?

X data repeats the same accounts and posts across pages, mentions and follow lists. In our 12-account import, 3,841 User rows collapsed into 2,174 User nodes and 20.4% of all MERGE rows matched something that already existed. With CREATE, every one of those would be a duplicate. MERGE plus a uniqueness constraint keeps one node per id.

Can Neo4j run PageRank on a Twitter follower graph?

Yes, with the Graph Data Science library: project the FOLLOWS relationships with gds.graph.project, then call gds.pageRank.stream (defaults: damping factor 0.85, 20 iterations). Run it on a graph with complete edges; on a sample made of a few follow lists, PageRank is nearly flat, and co-follow counts are the better signal.

Do I need the official X API to build a Twitter graph database?

No. Any source of posts and follow lists works. TwitterAPI.io returns posts at $0.15 per 1,000 and follow lists at 1 to 3 credits per record with no X developer account. The reads behind our sample graph cost under $0.21; the same reads on the official X API rate card come to $25.76.

Is Neo4j free for a Twitter graph project?

Neo4j has a Community Edition you can run yourself and a free tier of its Aura cloud service; the Graph Data Science library installs as a plugin on self-managed servers, with an Enterprise Edition that needs a license key. Check neo4j.com for the current tiers and limits before sizing a large graph.

How do I store a full reply thread in Neo4j?

Search for every post in the conversation with the query conversation_id:<id>, then import those posts with the same MERGE statement. Each reply's REPLIES_TO edge links to its parent, so a variable-length pattern such as [:REPLIES_TO*1..10] walks back to the root.

What is a Twitter knowledge graph?

A graph that adds entity nodes (organizations, domains, topics, products) next to the social layer of users and posts, linked by relationships such as LINKS_TO, ABOUT or WORKS_AT. The entities come from post URLs, bios, or an extraction model, and are imported with the same MERGE pattern.

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.