Skip to main content

Hashtags Feature

The Hashtags feature enables content discovery, categorization, and trending topic tracking across the platform.

What Hashtags Do in This Project

The hashtag system is a content organization and discovery engine that connects users with relevant content and helps surface trending topics. It serves multiple critical purposes:

1. Content Discovery & Organization

  • Categorizes posts by topics, making content easily searchable
  • Enables users to find content on specific subjects without following specific users
  • Organizes millions of posts into discoverable topic-based collections
  • Creates topic-based communities around shared interests
  • Automatically identifies what's popular right now using engagement velocity
  • Calculates trending metrics based on post frequency, unique users, and engagement
  • Surfaces viral content and emerging conversations
  • Helps users discover what's happening in real-time

3. Personalized Recommendations

  • Tracks user interactions with hashtags (views, likes, comments, shares)
  • Provides personalized hashtag suggestions based on interests
  • Powers recommendation algorithms for content discovery
  • Helps users discover new topics aligned with their preferences

4. Content Analytics & Insights

  • Tracks post counts per hashtag in real-time
  • Monitors engagement velocity (posts per hour)
  • Calculates trend factors to identify viral topics
  • Provides insights into content performance by topic

5. Social Engagement

  • Enables users to join conversations around topics
  • Connects users with similar interests
  • Facilitates community building around hashtags
  • Increases content reach through topic-based discovery

6. System Integration

  • Automatically extracts hashtags from post content
  • Normalizes hashtags for consistency (case-insensitive, special character removal)
  • Links posts to hashtags through PostHashtag relationships
  • Tracks user interactions for recommendation engine
  • Integrates with trending algorithms and analytics systems

Overview

Hashtags allow users to:

  • Categorize and discover content by topics
  • Track trending topics and conversations
  • Follow hashtags to see related content in their feed
  • Search for posts by hashtag
  • Discover new content based on hashtag interests

Using Hashtags in Posts

Creating Posts with Hashtags

Hashtags are automatically extracted from post content when you include the # symbol:

POST /api/Post/users/{userId}
Authorization: Bearer {token}
Content-Type: application/json

{
"content": "Just finished an amazing #photography session! #sunset #nature #photography",
"privacy": "public"
}

Hashtag Format:

  • Start with # symbol
  • Can contain letters, numbers, and underscores
  • Case-insensitive (automatically normalized)
  • Special characters are removed during normalization

Examples:

  • #photography → normalized to photography
  • #PhotoGraphy → normalized to photography
  • #photo_123 → normalized to photo_123
  • #photo-123 → normalized to photo123 (hyphen removed)

How Hashtags Work

Hashtag Lifecycle

  1. Extraction: When a post is created, hashtags are automatically extracted from content using regex pattern #[\w]+
  2. Normalization: Each hashtag is normalized (lowercase, special chars removed, # removed)
  3. Creation/Retrieval: System checks if hashtag exists, creates new one if needed
  4. Linking: Creates PostHashtag relationship linking post to hashtag
  5. Counting: Increments hashtag's PostCount in real-time
  6. Tracking: Records HashtagInteraction for user activity (created, viewed, liked, etc.)
  7. Trending Calculation: Background workers calculate trending metrics periodically
  8. Recommendation: System uses interaction history to suggest relevant hashtags

Hashtag Storage

Hashtags are stored in the database with their relationships to posts and trending metrics. The system maintains:

  • Hashtag entities with normalized names and post counts
  • Relationships between posts and hashtags
  • Trending metrics for popular hashtags
  • User interaction history for recommendations

Automatic Hashtag Processing

When a post is created with hashtags:

  • Hashtags are extracted from post content
  • Each hashtag is normalized to ensure consistency
  • New hashtags are automatically created if they don't exist
  • Post-hashtag relationships are established
  • Post counts are incremented
  • User interactions are tracked for recommendations

Searching Hashtags

Search Hashtags by Name

Purpose: Search for hashtags by name with autocomplete support. This endpoint is used for hashtag search functionality, autocomplete suggestions, and hashtag discovery.

Use Cases:

  • Autocomplete when typing hashtags in post composer
  • Search for specific hashtags
  • Discover hashtags matching a search term
  • Find hashtags before creating posts

When to Use:

  • User types # in post composer (trigger autocomplete)
  • User searches for hashtags in search bar
  • Displaying hashtag suggestions
  • Validating hashtag existence

Search Behavior:

  • Case-insensitive search
  • Partial matching (e.g., "photo" matches "photography", "photoshoot")
  • Returns results sorted by relevance (post count, popularity)
  • Limited results for performance (default: 10)

Search for hashtags by name with autocomplete support:

GET /api/hashtags/search?q=photo&limit=10
Authorization: Bearer {token}

Query Parameters:

  • q (required) - Search query (hashtag name)
  • limit (optional) - Maximum results (default: 10)

Response:

{
"success": true,
"data": [
{
"id": "hashtag-123",
"name": "photography",
"displayName": "Photography",
"description": null,
"postCount": 1250,
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-15T12:00:00Z"
},
{
"id": "hashtag-456",
"name": "photoshoot",
"displayName": "PhotoShoot",
"description": null,
"postCount": 342,
"createdAt": "2024-02-01T00:00:00Z",
"updatedAt": "2024-02-10T08:00:00Z"
}
]
}

Viewing Hashtag Details

Get Hashtag Information

Purpose: Retrieve comprehensive information about a specific hashtag, including trending metrics, post count, and personalized data. This is the primary endpoint for displaying hashtag pages.

Use Cases:

  • Display hashtag detail page
  • Show hashtag statistics and trending status
  • Get hashtag information before displaying posts
  • Check if hashtag is trending

When to Use:

  • User clicks on a hashtag link
  • Loading hashtag detail page
  • Displaying hashtag header with stats
  • Checking trending status for UI indicators

Response Includes:

  • Basic hashtag info (name, display name, description)
  • Post count (total posts using this hashtag)
  • Trending metrics (if available)
  • Personalized data (if userId provided)

Performance: Optimized query that includes trending data if available.

Get detailed information about a specific hashtag:

GET /api/hashtags/{hashtagName}?userId={userId}
Authorization: Bearer {token}

Path Parameters:

  • hashtagName - The hashtag name (without # symbol)

Query Parameters:

  • userId (optional) - User ID for personalized data

Response:

{
"success": true,
"data": {
"id": "hashtag-123",
"name": "photography",
"displayName": "Photography",
"description": "Share your photography work and tips",
"postCount": 1250,
"trending": {
"isTrending": true,
"trendFactor": 0.85,
"engagementVelocity": 12.5,
"postsLast24h": 45,
"postsLast7d": 280,
"uniqueUsersLast24h": 38
},
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-15T12:00:00Z"
}
}

Viewing Hashtag Posts

Get Posts with a Hashtag

Purpose: Retrieve posts that use a specific hashtag with pagination. This endpoint powers hashtag feed pages where users can browse all content tagged with a specific hashtag.

Use Cases:

  • Display hashtag feed page
  • Browse posts by topic
  • Show content related to a hashtag
  • Implement infinite scroll for hashtag feeds

When to Use:

  • Loading hashtag feed page
  • User navigates to a hashtag
  • Refreshing hashtag feed
  • Loading more posts (pagination)

Pagination:

  • Uses skip and limit for offset-based pagination
  • skip: Number of posts to skip (for pagination)
  • limit: Number of posts per page (default: 20)
  • Returns hasMore flag to indicate if more posts exist

Personalization:

  • requestingUserId enables personalized results
  • Can filter based on user's privacy settings
  • May prioritize posts from followed users

Performance: Efficient query that joins posts with hashtags and applies pagination.

Retrieve posts that use a specific hashtag:

GET /api/hashtags/{hashtagName}/posts?limit=20&skip=0&requestingUserId={userId}
Authorization: Bearer {token}

Path Parameters:

  • hashtagName - The hashtag name (without # symbol)

Query Parameters:

  • limit (optional) - Number of posts to return (default: 20)
  • skip (optional) - Number of posts to skip (default: 0)
  • requestingUserId (optional) - User ID for personalized results

Response:

{
"success": true,
"data": {
"hashtag": {
"name": "photography",
"displayName": "Photography",
"postCount": 1250
},
"posts": [
{
"id": "post-123",
"content": "Amazing sunset shot! #photography",
"author": {
"id": "user-456",
"fullName": "John Doe",
"username": "johndoe",
"avatar": "https://..."
},
"createdAt": "2024-01-15T10:00:00Z",
"reactionCount": 25,
"commentCount": 5,
"media": [...]
}
],
"pagination": {
"limit": 20,
"skip": 0,
"hasMore": true
}
}
}

Purpose: Retrieve hashtags that are currently trending based on engagement velocity, recent activity, and unique user participation. This powers the "Trending" section and helps users discover popular conversations.

Use Cases:

  • Display trending hashtags sidebar
  • Show "What's Trending" section
  • Discover popular topics
  • Join viral conversations

When to Use:

  • Loading trending hashtags widget
  • Displaying trending section on homepage
  • Refreshing trending list
  • Showing trending topics in search

Trending Algorithm:

  • Calculated by background workers periodically
  • Based on multiple factors:
    • Engagement Velocity: Posts per hour (higher = more trending)
    • Recent Activity: Posts in last 24 hours and 7 days
    • Unique Users: Number of different users (viral indicator)
    • Trend Factor: Combined score (0.0 - 1.0)

Ranking:

  • Results sorted by trendFactor (descending)
  • Includes rank number for display
  • Limited results for performance (default: 20)

Performance: Cached results updated periodically by background workers.

Discover what's trending right now:

GET /api/hashtags/trending?limit=20
Authorization: Bearer {token}

Query Parameters:

  • limit (optional) - Number of trending hashtags (default: 20)

Response:

{
"success": true,
"data": [
{
"id": "hashtag-123",
"name": "photography",
"displayName": "Photography",
"postCount": 1250,
"trending": {
"trendFactor": 0.92,
"engagementVelocity": 15.3,
"postsLast24h": 67,
"postsLast7d": 420,
"uniqueUsersLast24h": 52,
"rank": 1
}
},
{
"id": "hashtag-456",
"name": "sunset",
"displayName": "Sunset",
"postCount": 890,
"trending": {
"trendFactor": 0.78,
"engagementVelocity": 10.2,
"postsLast24h": 45,
"postsLast7d": 310,
"uniqueUsersLast24h": 38,
"rank": 2
}
}
]
}

Trending Metrics Explained:

  • Trend Factor (0.0 - 1.0): Overall trending score
  • Engagement Velocity: Posts per hour using this hashtag
  • Posts Last 24h: Number of posts in the last 24 hours
  • Posts Last 7d: Number of posts in the last 7 days
  • Unique Users Last 24h: Number of unique users who posted with this hashtag

Get Personalized Recommendations

Purpose: Get personalized hashtag recommendations based on user's interaction history, interests, and similar users' preferences. This helps users discover new topics aligned with their interests.

Use Cases:

  • Display "Suggested Hashtags" section
  • Show hashtag recommendations in post composer
  • Help users discover new interests
  • Personalize hashtag discovery

When to Use:

  • Loading hashtag suggestions widget
  • Displaying recommendations in post composer
  • Showing personalized hashtag feed
  • User exploring new topics

Recommendation Algorithm:

  • Based on user's interaction history with hashtags
  • Considers hashtags from posts user has liked/commented on
  • Analyzes similar users' hashtag preferences
  • Factors in trending hashtags in user's interest areas
  • Provides recommendation score (0.0 - 1.0) and reasons

Personalization Factors:

  • Hashtags from posts user interacted with
  • Hashtags from followed users
  • Similar users' popular hashtags
  • Trending hashtags in user's interest categories

Response Includes:

  • Recommended hashtags with scores
  • Explanation of why each hashtag is recommended
  • Post counts for context

Get hashtag recommendations based on your interests and activity:

GET /api/hashtags/recommended?userId={userId}&limit=10
Authorization: Bearer {token}

Query Parameters:

  • userId (required) - Your user ID
  • limit (optional) - Number of recommendations (default: 10)

Response:

{
"success": true,
"data": [
{
"id": "hashtag-789",
"name": "landscape",
"displayName": "Landscape",
"postCount": 650,
"recommendationScore": 0.85,
"reasons": [
"You frequently interact with #photography",
"Similar users also like this hashtag"
]
}
]
}

Hashtag Interactions

Automatic Tracking

The system automatically tracks your interactions with hashtags:

  • Created: When you create a post with a hashtag
  • Viewed: When you view posts with a hashtag
  • Liked: When you like a post with a hashtag
  • Commented: When you comment on a post with a hashtag
  • Shared: When you share a post with a hashtag

These interactions are used to:

  • Personalize your feed
  • Provide hashtag recommendations
  • Calculate trending metrics

Hashtag Normalization

Hashtags are automatically normalized to ensure consistency:

Normalization Rules:

  1. Remove # symbol if present
  2. Convert to lowercase
  3. Remove special characters (keep only letters, numbers, underscores)
  4. Trim whitespace

Examples:

  • #PhotoGraphyphotography
  • #photo-123photo123
  • #photo_123photo_123
  • # photo photo

API Endpoints Summary

Search Hashtags (GET /api/hashtags/search)

Purpose: Autocomplete and search functionality for finding hashtags by name.

Key Features:

  • Partial matching (e.g., "photo" matches "photography")
  • Case-insensitive search
  • Sorted by relevance (post count)
  • Limited results for performance

When to Use: Post composer autocomplete, hashtag search bar


Get Hashtag Details (GET /api/hashtags/{hashtagName})

Purpose: Retrieve comprehensive hashtag information including trending metrics.

Key Features:

  • Returns hashtag metadata (name, description, post count)
  • Includes trending metrics if available
  • Supports personalized data with userId parameter

When to Use: Loading hashtag detail page, displaying hashtag header


Get Hashtag Posts (GET /api/hashtags/{hashtagName}/posts)

Purpose: Retrieve posts tagged with a specific hashtag with pagination.

Key Features:

  • Offset-based pagination (skip/limit)
  • Personalized results with requestingUserId
  • Returns hashtag context with posts
  • Efficient query with joins

When to Use: Displaying hashtag feed, browsing posts by topic


Purpose: Discover currently trending hashtags based on engagement metrics.

Key Features:

  • Sorted by trend factor (most trending first)
  • Includes ranking information
  • Cached results for performance
  • Updated periodically by background workers

When to Use: Trending sidebar, "What's Trending" section, homepage widgets


Purpose: Get personalized hashtag suggestions based on user interests.

Key Features:

  • Personalized recommendations with scores
  • Explains why each hashtag is recommended
  • Based on interaction history and similar users
  • Helps discover new topics

When to Use: Hashtag suggestions widget, post composer recommendations

Best Practices

Using Hashtags Effectively

  1. Be Specific: Use relevant, specific hashtags

    • ✅ Good: #sunsetphotography, #naturephotography, #wildlifephotography
    • ❌ Avoid: #photo, #pic, #insta (too generic, millions of posts)
  2. Don't Overuse: 3-5 hashtags per post is optimal

    • Too many hashtags can look spammy and reduce engagement
    • Focus on the most relevant tags for your content
    • Quality over quantity
  3. Mix Popular and Niche: Combine trending and specific hashtags

    • Popular hashtags: #photography, #nature (broad reach, high competition)
    • Niche hashtags: #sunsetphotography, #wildlifephotography (targeted audience, less competition)
    • Balance helps reach both broad and specific audiences
  4. Research Trends: Check trending hashtags before posting

    • Use trending hashtags when relevant to your content
    • Join conversations around trending topics
    • Avoid using trending hashtags unrelated to your content (spam)
  5. Create Your Own: Use unique hashtags for events or campaigns

    • Example: #MyCompanyEvent2024, #SummerChallenge2024
    • Helps track specific conversations and campaigns
    • Builds community around your brand or event
  6. Use Location Hashtags: Include location when relevant

    • Example: #NewYorkPhotography, #ParisTravel
    • Helps local discovery and community building
  7. Follow Hashtag Etiquette:

    • Don't hijack unrelated trending hashtags
    • Use appropriate hashtags for your content
    • Respect hashtag communities

Hashtag Discovery

  • Browse Trending: Check trending hashtags regularly to discover popular topics
  • Use Search: Search for hashtags to find related tags and communities
  • Check Recommendations: Review recommended hashtags based on your interests
  • Explore Followed Users: See what hashtags people you follow are using
  • Analyze Performance: Check which hashtags drive the most engagement for your content

For Developers

  1. Normalization: Always normalize hashtags before storing (use Hashtag.NormalizeHashtag())
  2. Extraction: Use regex pattern /#[\w]+/g to extract hashtags from text
  3. Validation: Validate hashtag format before processing
  4. Caching: Cache trending hashtags and popular searches for performance
  5. Indexing: Ensure hashtag name is indexed for fast search queries
  6. Real-time Updates: Update post counts atomically to ensure accuracy
  7. Background Processing: Use background workers for trending calculations

Hashtag Architecture

System Components

  1. Domain Layer (Domain/Modules/Hashtag)

    • Hashtag aggregate: Core hashtag entity with normalization logic
    • HashtagTrends: Trending metrics calculation
    • HashtagInteraction: User interaction tracking
    • PostHashtag: Post-hashtag relationship
  2. Application Layer (Application/Modules/Hashtag)

    • Queries: Search, get details, get posts, trending, recommendations
    • Commands: (Future: Create, update, delete hashtags)
  3. Infrastructure Layer

    • PostgreSQL: Primary storage for hashtags and relationships
    • Elasticsearch: (Optional) Full-text search for hashtags
    • Redis: Caching for trending hashtags and popular searches
  4. Background Workers

    • TrendingWorker: Calculates trending metrics periodically
    • InteractionWorker: Processes hashtag interactions
    • RecommendationWorker: Generates personalized recommendations

Hashtag Flow

User Creates Post with Hashtags

Extract Hashtags from Content (#photography, #sunset)

Normalize Each Hashtag (photography, sunset)

Check/Create Hashtag Entities

Create PostHashtag Relationships

Increment PostCount for Each Hashtag

Record HashtagInteraction (created)

Background Workers Calculate Trending Metrics

Update HashtagTrends with New Metrics

Recommendation Engine Uses Interactions

Hashtag Analytics

Post Count

Purpose: Real-time tracking of how many posts use each hashtag. This metric indicates hashtag popularity and helps users understand hashtag usage.

How It Works:

  • Incremented when a post with the hashtag is created
  • Decremented when a post is deleted
  • Updated atomically to ensure accuracy
  • Visible in hashtag details and search results

Use Cases:

  • Display hashtag popularity
  • Sort search results by popularity
  • Filter hashtags by minimum post count
  • Show hashtag growth over time

Purpose: Calculate and track trending status for hashtags to identify viral topics and emerging conversations.

Metrics Tracked:

  1. Engagement Velocity (Posts/Hour)

    • Measures how quickly posts are being created
    • Higher velocity = more trending
    • Calculated: postsLast24h / 24
  2. Trend Factor (0.0 - 1.0)

    • Combined score indicating trending status
    • Factors: velocity, unique users, recent activity
    • Closer to 1.0 = more trending
  3. Posts Last 24h

    • Number of posts in the last 24 hours
    • Indicates recent activity spike
  4. Posts Last 7d

    • Number of posts in the last 7 days
    • Shows sustained interest
  5. Unique Users Last 24h

    • Number of different users who posted
    • Indicates viral spread (not just one user)

Calculation:

  • Background workers calculate metrics periodically
  • Updates HashtagTrends entity with latest metrics
  • Cached for performance
  • Recalculated when new posts are created

Trending hashtags are calculated based on:

  • Engagement Velocity: How quickly posts are being created
  • Recent Activity: Posts in the last 24 hours and 7 days
  • Unique Users: Number of different users using the hashtag
  • Trend Factor: Combined score indicating trending status

API Reference

Hashtag endpoints are under api/Hashtags (search, get by name, get posts, trending, recommended). See the API Intro route table and Search for Elasticsearch integration.