[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BV13D87X42AJTRQ4ECS2PF":3,"skill-same:01M7BV13D87X42AJTRQ4ECS2PF":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BV13D87X42AJTRQ4ECS2PF","hybrid-search-implementation",null,"Combine vector and keyword search for improved retrieval. Use when implementing RAG systems, building search engines, or when neither approach alone provides sufficient recall.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-external_plugins\u002Fllm-application-dev\u002Fskills\u002Fhybrid-search-implementation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: hybrid-search-implementation\ndescription: Combine vector and keyword search for improved retrieval. Use when implementing RAG systems, building search engines, or when neither approach alone provides sufficient recall.\n---\n\n# Hybrid Search Implementation\n\nPatterns for combining vector similarity and keyword-based search.\n\n## When to Use This Skill\n\n- Building RAG systems with improved recall\n- Combining semantic understanding with exact matching\n- Handling queries with specific terms (names, codes)\n- Improving search for domain-specific vocabulary\n- When pure vector search misses keyword matches\n\n## Core Concepts\n\n### 1. Hybrid Search Architecture\n\n```\nQuery → ┬─► Vector Search ──► Candidates ─┐\n        │                                  │\n        └─► Keyword Search ─► Candidates ─┴─► Fusion ─► Results\n```\n\n### 2. Fusion Methods\n\n| Method | Description | Best For |\n|--------|-------------|----------|\n| **RRF** | Reciprocal Rank Fusion | General purpose |\n| **Linear** | Weighted sum of scores | Tunable balance |\n| **Cross-encoder** | Rerank with neural model | Highest quality |\n| **Cascade** | Filter then rerank | Efficiency |\n\n## Templates\n\n### Template 1: Reciprocal Rank Fusion\n\n```python\nfrom typing import List, Dict, Tuple\nfrom collections import defaultdict\n\ndef reciprocal_rank_fusion(\n    result_lists: List[List[Tuple[str, float]]],\n    k: int = 60,\n    weights: List[float] = None\n) -> List[Tuple[str, float]]:\n    \"\"\"\n    Combine multiple ranked lists using RRF.\n\n    Args:\n        result_lists: List of (doc_id, score) tuples per search method\n        k: RRF constant (higher = more weight to lower ranks)\n        weights: Optional weights per result list\n\n    Returns:\n        Fused ranking as (doc_id, score) tuples\n    \"\"\"\n    if weights is None:\n        weights = [1.0] * len(result_lists)\n\n    scores = defaultdict(float)\n\n    for result_list, weight in zip(result_lists, weights):\n        for rank, (doc_id, _) in enumerate(result_list):\n            # RRF formula: 1 \u002F (k + rank)\n            scores[doc_id] += weight * (1.0 \u002F (k + rank + 1))\n\n    # Sort by fused score\n    return sorted(scores.items(), key=lambda x: x[1], reverse=True)\n\n\ndef linear_combination(\n    vector_results: List[Tuple[str, float]],\n    keyword_results: List[Tuple[str, float]],\n    alpha: float = 0.5\n) -> List[Tuple[str, float]]:\n    \"\"\"\n    Combine results with linear interpolation.\n\n    Args:\n        vector_results: (doc_id, similarity_score) from vector search\n        keyword_results: (doc_id, bm25_score) from keyword search\n        alpha: Weight for vector search (1-alpha for keyword)\n    \"\"\"\n    # Normalize scores to [0, 1]\n    def normalize(results):\n        if not results:\n            return {}\n        scores = [s for _, s in results]\n        min_s, max_s = min(scores), max(scores)\n        range_s = max_s - min_s if max_s != min_s else 1\n        return {doc_id: (score - min_s) \u002F range_s for doc_id, score in results}\n\n    vector_scores = normalize(vector_results)\n    keyword_scores = normalize(keyword_results)\n\n    # Combine\n    all_docs = set(vector_scores.keys()) | set(keyword_scores.keys())\n    combined = {}\n\n    for doc_id in all_docs:\n        v_score = vector_scores.get(doc_id, 0)\n        k_score = keyword_scores.get(doc_id, 0)\n        combined[doc_id] = alpha * v_score + (1 - alpha) * k_score\n\n    return sorted(combined.items(), key=lambda x: x[1], reverse=True)\n```\n\n### Template 2: PostgreSQL Hybrid Search\n\n```python\nimport asyncpg\nfrom typing import List, Dict, Optional\nimport numpy as np\n\nclass PostgresHybridSearch:\n    \"\"\"Hybrid search with pgvector and full-text search.\"\"\"\n\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def setup_schema(self):\n        \"\"\"Create tables and indexes.\"\"\"\n        async with self.pool.acquire() as conn:\n            await conn.execute(\"\"\"\n                CREATE EXTENSION IF NOT EXISTS vector;\n\n                CREATE TABLE IF NOT EXISTS documents (\n                    id TEXT PRIMARY KEY,\n                    content TEXT NOT NULL,\n                    embedding vector(1536),\n                    metadata JSONB DEFAULT '{}',\n                    ts_content tsvector GENERATED ALWAYS AS (\n                        to_tsvector('english', content)\n                    ) STORED\n                );\n\n                -- Vector index (HNSW)\n                CREATE INDEX IF NOT EXISTS documents_embedding_idx\n                ON documents USING hnsw (embedding vector_cosine_ops);\n\n                -- Full-text index (GIN)\n                CREATE INDEX IF NOT EXISTS documents_fts_idx\n                ON documents USING gin (ts_content);\n            \"\"\")\n\n    async def hybrid_search(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        vector_weight: float = 0.5,\n        filter_metadata: Optional[Dict] = None\n    ) -> List[Dict]:\n        \"\"\"\n        Perform hybrid search combining vector and full-text.\n\n        Uses RRF fusion for combining results.\n        \"\"\"\n        async with self.pool.acquire() as conn:\n            # Build filter clause\n            where_clause = \"1=1\"\n            params = [query_embedding, query, limit * 3]\n\n            if filter_metadata:\n                for key, value in filter_metadata.items():\n                    params.append(value)\n                    where_clause += f\" AND metadata->>'{key}' = ${len(params)}\"\n\n            results = await conn.fetch(f\"\"\"\n                WITH vector_search AS (\n                    SELECT\n                        id,\n                        content,\n                        metadata,\n                        ROW_NUMBER() OVER (ORDER BY embedding \u003C=> $1::vector) as vector_rank,\n                        1 - (embedding \u003C=> $1::vector) as vector_score\n                    FROM documents\n                    WHERE {where_clause}\n                    ORDER BY embedding \u003C=> $1::vector\n                    LIMIT $3\n                ),\n                keyword_search AS (\n                    SELECT\n                        id,\n                        content,\n                        metadata,\n                        ROW_NUMBER() OVER (ORDER BY ts_rank(ts_content, websearch_to_tsquery('english', $2)) DESC) as keyword_rank,\n                        ts_rank(ts_content, websearch_to_tsquery('english', $2)) as keyword_score\n                    FROM documents\n                    WHERE ts_content @@ websearch_to_tsquery('english', $2)\n                      AND {where_clause}\n                    ORDER BY ts_rank(ts_content, websearch_to_tsquery('english', $2)) DESC\n                    LIMIT $3\n                )\n                SELECT\n                    COALESCE(v.id, k.id) as id,\n                    COALESCE(v.content, k.content) as content,\n                    COALESCE(v.metadata, k.metadata) as metadata,\n                    v.vector_score,\n                    k.keyword_score,\n                    -- RRF fusion\n                    COALESCE(1.0 \u002F (60 + v.vector_rank), 0) * $4::float +\n                    COALESCE(1.0 \u002F (60 + k.keyword_rank), 0) * (1 - $4::float) as rrf_score\n                FROM vector_search v\n                FULL OUTER JOIN keyword_search k ON v.id = k.id\n                ORDER BY rrf_score DESC\n                LIMIT $3 \u002F 3\n            \"\"\", *params, vector_weight)\n\n            return [dict(row) for row in results]\n\n    async def search_with_rerank(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        rerank_candidates: int = 50\n    ) -> List[Dict]:\n        \"\"\"Hybrid search with cross-encoder reranking.\"\"\"\n        from sentence_transformers import CrossEncoder\n\n        # Get candidates\n        candidates = await self.hybrid_search(\n            query, query_embedding, limit=rerank_candidates\n        )\n\n        if not candidates:\n            return []\n\n        # Rerank with cross-encoder\n        model = CrossEncoder('cross-encoder\u002Fms-marco-MiniLM-L-6-v2')\n\n        pairs = [(query, c[\"content\"]) for c in candidates]\n        scores = model.predict(pairs)\n\n        for candidate, score in zip(candidates, scores):\n            candidate[\"rerank_score\"] = float(score)\n\n        # Sort by rerank score and return top results\n        reranked = sorted(candidates, key=lambda x: x[\"rerank_score\"], reverse=True)\n        return reranked[:limit]\n```\n\n### Template 3: Elasticsearch Hybrid Search\n\n```python\nfrom elasticsearch import Elasticsearch\nfrom typing import List, Dict, Optional\n\nclass ElasticsearchHybridSearch:\n    \"\"\"Hybrid search with Elasticsearch and dense vectors.\"\"\"\n\n    def __init__(\n        self,\n        es_client: Elasticsearch,\n        index_name: str = \"documents\"\n    ):\n        self.es = es_client\n        self.index_name = index_name\n\n    def create_index(self, vector_dims: int = 1536):\n        \"\"\"Create index with dense vector and text fields.\"\"\"\n        mapping = {\n            \"mappings\": {\n                \"properties\": {\n                    \"content\": {\n                        \"type\": \"text\",\n                        \"analyzer\": \"english\"\n                    },\n                    \"embedding\": {\n                        \"type\": \"dense_vector\",\n                        \"dims\": vector_dims,\n                        \"index\": True,\n                        \"similarity\": \"cosine\"\n                    },\n                    \"metadata\": {\n                        \"type\": \"object\",\n                        \"enabled\": True\n                    }\n                }\n            }\n        }\n        self.es.indices.create(index=self.index_name, body=mapping, ignore=400)\n\n    def hybrid_search(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        boost_vector: float = 1.0,\n        boost_text: float = 1.0,\n        filter: Optional[Dict] = None\n    ) -> List[Dict]:\n        \"\"\"\n        Hybrid search using Elasticsearch's built-in capabilities.\n        \"\"\"\n        # Build the hybrid query\n        search_body = {\n            \"size\": limit,\n            \"query\": {\n                \"bool\": {\n                    \"should\": [\n                        # Vector search (kNN)\n                        {\n                            \"script_score\": {\n                                \"query\": {\"match_all\": {}},\n                                \"script\": {\n                                    \"source\": f\"cosineSimilarity(params.query_vector, 'embedding') * {boost_vector} + 1.0\",\n                                    \"params\": {\"query_vector\": query_embedding}\n                                }\n                            }\n                        },\n                        # Text search (BM25)\n                        {\n                            \"match\": {\n                                \"content\": {\n                                    \"query\": query,\n                                    \"boost\": boost_text\n                                }\n                            }\n                        }\n                    ],\n                    \"minimum_should_match\": 1\n                }\n            }\n        }\n\n        # Add filter if provided\n        if filter:\n            search_body[\"query\"][\"bool\"][\"filter\"] = filter\n\n        response = self.es.search(index=self.index_name, body=search_body)\n\n        return [\n            {\n                \"id\": hit[\"_id\"],\n                \"content\": hit[\"_source\"][\"content\"],\n                \"metadata\": hit[\"_source\"].get(\"metadata\", {}),\n                \"score\": hit[\"_score\"]\n            }\n            for hit in response[\"hits\"][\"hits\"]\n        ]\n\n    def hybrid_search_rrf(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        window_size: int = 100\n    ) -> List[Dict]:\n        \"\"\"\n        Hybrid search using Elasticsearch 8.x RRF.\n        \"\"\"\n        search_body = {\n            \"size\": limit,\n            \"sub_searches\": [\n                {\n                    \"query\": {\n                        \"match\": {\n                            \"content\": query\n                        }\n                    }\n                },\n                {\n                    \"query\": {\n                        \"knn\": {\n                            \"field\": \"embedding\",\n                            \"query_vector\": query_embedding,\n                            \"k\": window_size,\n                            \"num_candidates\": window_size * 2\n                        }\n                    }\n                }\n            ],\n            \"rank\": {\n                \"rrf\": {\n                    \"window_size\": window_size,\n                    \"rank_constant\": 60\n                }\n            }\n        }\n\n        response = self.es.search(index=self.index_name, body=search_body)\n\n        return [\n            {\n                \"id\": hit[\"_id\"],\n                \"content\": hit[\"_source\"][\"content\"],\n                \"score\": hit[\"_score\"]\n            }\n            for hit in response[\"hits\"][\"hits\"]\n        ]\n```\n\n### Template 4: Custom Hybrid RAG Pipeline\n\n```python\nfrom typing import List, Dict, Optional, Callable\nfrom dataclasses import dataclass\n\n@dataclass\nclass SearchResult:\n    id: str\n    content: str\n    score: float\n    source: str  # \"vector\", \"keyword\", \"hybrid\"\n    metadata: Dict = None\n\n\nclass HybridRAGPipeline:\n    \"\"\"Complete hybrid search pipeline for RAG.\"\"\"\n\n    def __init__(\n        self,\n        vector_store,\n        keyword_store,\n        embedder,\n        reranker=None,\n        fusion_method: str = \"rrf\",\n        vector_weight: float = 0.5\n    ):\n        self.vector_store = vector_store\n        self.keyword_store = keyword_store\n        self.embedder = embedder\n        self.reranker = reranker\n        self.fusion_method = fusion_method\n        self.vector_weight = vector_weight\n\n    async def search(\n        self,\n        query: str,\n        top_k: int = 10,\n        filter: Optional[Dict] = None,\n        use_rerank: bool = True\n    ) -> List[SearchResult]:\n        \"\"\"Execute hybrid search pipeline.\"\"\"\n\n        # Step 1: Get query embedding\n        query_embedding = self.embedder.embed(query)\n\n        # Step 2: Execute parallel searches\n        vector_results, keyword_results = await asyncio.gather(\n            self._vector_search(query_embedding, top_k * 3, filter),\n            self._keyword_search(query, top_k * 3, filter)\n        )\n\n        # Step 3: Fuse results\n        if self.fusion_method == \"rrf\":\n            fused = self._rrf_fusion(vector_results, keyword_results)\n        else:\n            fused = self._linear_fusion(vector_results, keyword_results)\n\n        # Step 4: Rerank if enabled\n        if use_rerank and self.reranker:\n            fused = await self._rerank(query, fused[:top_k * 2])\n\n        return fused[:top_k]\n\n    async def _vector_search(\n        self,\n        embedding: List[float],\n        limit: int,\n        filter: Dict\n    ) -> List[SearchResult]:\n        results = await self.vector_store.search(embedding, limit, filter)\n        return [\n            SearchResult(\n                id=r[\"id\"],\n                content=r[\"content\"],\n                score=r[\"score\"],\n                source=\"vector\",\n                metadata=r.get(\"metadata\")\n            )\n            for r in results\n        ]\n\n    async def _keyword_search(\n        self,\n        query: str,\n        limit: int,\n        filter: Dict\n    ) -> List[SearchResult]:\n        results = await self.keyword_store.search(query, limit, filter)\n        return [\n            SearchResult(\n                id=r[\"id\"],\n                content=r[\"content\"],\n                score=r[\"score\"],\n                source=\"keyword\",\n                metadata=r.get(\"metadata\")\n            )\n            for r in results\n        ]\n\n    def _rrf_fusion(\n        self,\n        vector_results: List[SearchResult],\n        keyword_results: List[SearchResult]\n    ) -> List[SearchResult]:\n        \"\"\"Fuse with RRF.\"\"\"\n        k = 60\n        scores = {}\n        content_map = {}\n\n        for rank, result in enumerate(vector_results):\n            scores[result.id] = scores.get(result.id, 0) + 1 \u002F (k + rank + 1)\n            content_map[result.id] = result\n\n        for rank, result in enumerate(keyword_results):\n            scores[result.id] = scores.get(result.id, 0) + 1 \u002F (k + rank + 1)\n            if result.id not in content_map:\n                content_map[result.id] = result\n\n        sorted_ids = sorted(scores.keys(), key=lambda x: scores[x], reverse=True)\n\n        return [\n            SearchResult(\n                id=doc_id,\n                content=content_map[doc_id].content,\n                score=scores[doc_id],\n                source=\"hybrid\",\n                metadata=content_map[doc_id].metadata\n            )\n            for doc_id in sorted_ids\n        ]\n\n    async def _rerank(\n        self,\n        query: str,\n        results: List[SearchResult]\n    ) -> List[SearchResult]:\n        \"\"\"Rerank with cross-encoder.\"\"\"\n        if not results:\n            return results\n\n        pairs = [(query, r.content) for r in results]\n        scores = self.reranker.predict(pairs)\n\n        for result, score in zip(results, scores):\n            result.score = float(score)\n\n        return sorted(results, key=lambda x: x.score, reverse=True)\n```\n\n## Best Practices\n\n### Do's\n- **Tune weights empirically** - Test on your data\n- **Use RRF for simplicity** - Works well without tuning\n- **Add reranking** - Significant quality improvement\n- **Log both scores** - Helps with debugging\n- **A\u002FB test** - Measure real user impact\n\n### Don'ts\n- **Don't assume one size fits all** - Different queries need different weights\n- **Don't skip keyword search** - Handles exact matches better\n- **Don't over-fetch** - Balance recall vs latency\n- **Don't ignore edge cases** - Empty results, single word queries\n\n## Resources\n\n- [RRF Paper](https:\u002F\u002Fplg.uwaterloo.ca\u002F~gvcormac\u002Fcormacksigir09-rrf.pdf)\n- [Vespa Hybrid Search](https:\u002F\u002Fblog.vespa.ai\u002Fimproving-text-ranking-with-few-shot-prompting\u002F)\n- [Cohere Rerank](https:\u002F\u002Fdocs.cohere.com\u002Fdocs\u002Freranking)\n","# Hybrid Search Implementation\n\nPatterns for combining vector similarity and keyword-based search.\n\n## When to Use This Skill\n\n- Building RAG systems with improved recall\n- Combining semantic understanding with exact matching\n- Handling queries with specific terms (names, codes)\n- Improving search for domain-specific vocabulary\n- When pure vector search misses keyword matches\n\n## Core Concepts\n\n### 1. Hybrid Search Architecture\n\n```\nQuery → ┬─► Vector Search ──► Candidates ─┐\n        │                                  │\n        └─► Keyword Search ─► Candidates ─┴─► Fusion ─► Results\n```\n\n### 2. Fusion Methods\n\n| Method | Description | Best For |\n|--------|-------------|----------|\n| **RRF** | Reciprocal Rank Fusion | General purpose |\n| **Linear** | Weighted sum of scores | Tunable balance |\n| **Cross-encoder** | Rerank with neural model | Highest quality |\n| **Cascade** | Filter then rerank | Efficiency |\n\n## Templates\n\n### Template 1: Reciprocal Rank Fusion\n\n```python\nfrom typing import List, Dict, Tuple\nfrom collections import defaultdict\n\ndef reciprocal_rank_fusion(\n    result_lists: List[List[Tuple[str, float]]],\n    k: int = 60,\n    weights: List[float] = None\n) -> List[Tuple[str, float]]:\n    \"\"\"\n    Combine multiple ranked lists using RRF.\n\n    Args:\n        result_lists: List of (doc_id, score) tuples per search method\n        k: RRF constant (higher = more weight to lower ranks)\n        weights: Optional weights per result list\n\n    Returns:\n        Fused ranking as (doc_id, score) tuples\n    \"\"\"\n    if weights is None:\n        weights = [1.0] * len(result_lists)\n\n    scores = defaultdict(float)\n\n    for result_list, weight in zip(result_lists, weights):\n        for rank, (doc_id, _) in enumerate(result_list):\n            # RRF formula: 1 \u002F (k + rank)\n            scores[doc_id] += weight * (1.0 \u002F (k + rank + 1))\n\n    # Sort by fused score\n    return sorted(scores.items(), key=lambda x: x[1], reverse=True)\n\n\ndef linear_combination(\n    vector_results: List[Tuple[str, float]],\n    keyword_results: List[Tuple[str, float]],\n    alpha: float = 0.5\n) -> List[Tuple[str, float]]:\n    \"\"\"\n    Combine results with linear interpolation.\n\n    Args:\n        vector_results: (doc_id, similarity_score) from vector search\n        keyword_results: (doc_id, bm25_score) from keyword search\n        alpha: Weight for vector search (1-alpha for keyword)\n    \"\"\"\n    # Normalize scores to [0, 1]\n    def normalize(results):\n        if not results:\n            return {}\n        scores = [s for _, s in results]\n        min_s, max_s = min(scores), max(scores)\n        range_s = max_s - min_s if max_s != min_s else 1\n        return {doc_id: (score - min_s) \u002F range_s for doc_id, score in results}\n\n    vector_scores = normalize(vector_results)\n    keyword_scores = normalize(keyword_results)\n\n    # Combine\n    all_docs = set(vector_scores.keys()) | set(keyword_scores.keys())\n    combined = {}\n\n    for doc_id in all_docs:\n        v_score = vector_scores.get(doc_id, 0)\n        k_score = keyword_scores.get(doc_id, 0)\n        combined[doc_id] = alpha * v_score + (1 - alpha) * k_score\n\n    return sorted(combined.items(), key=lambda x: x[1], reverse=True)\n```\n\n### Template 2: PostgreSQL Hybrid Search\n\n```python\nimport asyncpg\nfrom typing import List, Dict, Optional\nimport numpy as np\n\nclass PostgresHybridSearch:\n    \"\"\"Hybrid search with pgvector and full-text search.\"\"\"\n\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def setup_schema(self):\n        \"\"\"Create tables and indexes.\"\"\"\n        async with self.pool.acquire() as conn:\n            await conn.execute(\"\"\"\n                CREATE EXTENSION IF NOT EXISTS vector;\n\n                CREATE TABLE IF NOT EXISTS documents (\n                    id TEXT PRIMARY KEY,\n                    content TEXT NOT NULL,\n                    embedding vector(1536),\n                    metadata JSONB DEFAULT '{}',\n                    ts_content tsvector GENERATED ALWAYS AS (\n                        to_tsvector('english', content)\n                    ) STORED\n                );\n\n                -- Vector index (HNSW)\n                CREATE INDEX IF NOT EXISTS documents_embedding_idx\n                ON documents USING hnsw (embedding vector_cosine_ops);\n\n                -- Full-text index (GIN)\n                CREATE INDEX IF NOT EXISTS documents_fts_idx\n                ON documents USING gin (ts_content);\n            \"\"\")\n\n    async def hybrid_search(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        vector_weight: float = 0.5,\n        filter_metadata: Optional[Dict] = None\n    ) -> List[Dict]:\n        \"\"\"\n        Perform hybrid search combining vector and full-text.\n\n        Uses RRF fusion for combining results.\n        \"\"\"\n        async with self.pool.acquire() as conn:\n            # Build filter clause\n            where_clause = \"1=1\"\n            params = [query_embedding, query, limit * 3]\n\n            if filter_metadata:\n                for key, value in filter_metadata.items():\n                    params.append(value)\n                    where_clause += f\" AND metadata->>'{key}' = ${len(params)}\"\n\n            results = await conn.fetch(f\"\"\"\n                WITH vector_search AS (\n                    SELECT\n                        id,\n                        content,\n                        metadata,\n                        ROW_NUMBER() OVER (ORDER BY embedding \u003C=> $1::vector) as vector_rank,\n                        1 - (embedding \u003C=> $1::vector) as vector_score\n                    FROM documents\n                    WHERE {where_clause}\n                    ORDER BY embedding \u003C=> $1::vector\n                    LIMIT $3\n                ),\n                keyword_search AS (\n                    SELECT\n                        id,\n                        content,\n                        metadata,\n                        ROW_NUMBER() OVER (ORDER BY ts_rank(ts_content, websearch_to_tsquery('english', $2)) DESC) as keyword_rank,\n                        ts_rank(ts_content, websearch_to_tsquery('english', $2)) as keyword_score\n                    FROM documents\n                    WHERE ts_content @@ websearch_to_tsquery('english', $2)\n                      AND {where_clause}\n                    ORDER BY ts_rank(ts_content, websearch_to_tsquery('english', $2)) DESC\n                    LIMIT $3\n                )\n                SELECT\n                    COALESCE(v.id, k.id) as id,\n                    COALESCE(v.content, k.content) as content,\n                    COALESCE(v.metadata, k.metadata) as metadata,\n                    v.vector_score,\n                    k.keyword_score,\n                    -- RRF fusion\n                    COALESCE(1.0 \u002F (60 + v.vector_rank), 0) * $4::float +\n                    COALESCE(1.0 \u002F (60 + k.keyword_rank), 0) * (1 - $4::float) as rrf_score\n                FROM vector_search v\n                FULL OUTER JOIN keyword_search k ON v.id = k.id\n                ORDER BY rrf_score DESC\n                LIMIT $3 \u002F 3\n            \"\"\", *params, vector_weight)\n\n            return [dict(row) for row in results]\n\n    async def search_with_rerank(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        rerank_candidates: int = 50\n    ) -> List[Dict]:\n        \"\"\"Hybrid search with cross-encoder reranking.\"\"\"\n        from sentence_transformers import CrossEncoder\n\n        # Get candidates\n        candidates = await self.hybrid_search(\n            query, query_embedding, limit=rerank_candidates\n        )\n\n        if not candidates:\n            return []\n\n        # Rerank with cross-encoder\n        model = CrossEncoder('cross-encoder\u002Fms-marco-MiniLM-L-6-v2')\n\n        pairs = [(query, c[\"content\"]) for c in candidates]\n        scores = model.predict(pairs)\n\n        for candidate, score in zip(candidates, scores):\n            candidate[\"rerank_score\"] = float(score)\n\n        # Sort by rerank score and return top results\n        reranked = sorted(candidates, key=lambda x: x[\"rerank_score\"], reverse=True)\n        return reranked[:limit]\n```\n\n### Template 3: Elasticsearch Hybrid Search\n\n```python\nfrom elasticsearch import Elasticsearch\nfrom typing import List, Dict, Optional\n\nclass ElasticsearchHybridSearch:\n    \"\"\"Hybrid search with Elasticsearch and dense vectors.\"\"\"\n\n    def __init__(\n        self,\n        es_client: Elasticsearch,\n        index_name: str = \"documents\"\n    ):\n        self.es = es_client\n        self.index_name = index_name\n\n    def create_index(self, vector_dims: int = 1536):\n        \"\"\"Create index with dense vector and text fields.\"\"\"\n        mapping = {\n            \"mappings\": {\n                \"properties\": {\n                    \"content\": {\n                        \"type\": \"text\",\n                        \"analyzer\": \"english\"\n                    },\n                    \"embedding\": {\n                        \"type\": \"dense_vector\",\n                        \"dims\": vector_dims,\n                        \"index\": True,\n                        \"similarity\": \"cosine\"\n                    },\n                    \"metadata\": {\n                        \"type\": \"object\",\n                        \"enabled\": True\n                    }\n                }\n            }\n        }\n        self.es.indices.create(index=self.index_name, body=mapping, ignore=400)\n\n    def hybrid_search(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        boost_vector: float = 1.0,\n        boost_text: float = 1.0,\n        filter: Optional[Dict] = None\n    ) -> List[Dict]:\n        \"\"\"\n        Hybrid search using Elasticsearch's built-in capabilities.\n        \"\"\"\n        # Build the hybrid query\n        search_body = {\n            \"size\": limit,\n            \"query\": {\n                \"bool\": {\n                    \"should\": [\n                        # Vector search (kNN)\n                        {\n                            \"script_score\": {\n                                \"query\": {\"match_all\": {}},\n                                \"script\": {\n                                    \"source\": f\"cosineSimilarity(params.query_vector, 'embedding') * {boost_vector} + 1.0\",\n                                    \"params\": {\"query_vector\": query_embedding}\n                                }\n                            }\n                        },\n                        # Text search (BM25)\n                        {\n                            \"match\": {\n                                \"content\": {\n                                    \"query\": query,\n                                    \"boost\": boost_text\n                                }\n                            }\n                        }\n                    ],\n                    \"minimum_should_match\": 1\n                }\n            }\n        }\n\n        # Add filter if provided\n        if filter:\n            search_body[\"query\"][\"bool\"][\"filter\"] = filter\n\n        response = self.es.search(index=self.index_name, body=search_body)\n\n        return [\n            {\n                \"id\": hit[\"_id\"],\n                \"content\": hit[\"_source\"][\"content\"],\n                \"metadata\": hit[\"_source\"].get(\"metadata\", {}),\n                \"score\": hit[\"_score\"]\n            }\n            for hit in response[\"hits\"][\"hits\"]\n        ]\n\n    def hybrid_search_rrf(\n        self,\n        query: str,\n        query_embedding: List[float],\n        limit: int = 10,\n        window_size: int = 100\n    ) -> List[Dict]:\n        \"\"\"\n        Hybrid search using Elasticsearch 8.x RRF.\n        \"\"\"\n        search_body = {\n            \"size\": limit,\n            \"sub_searches\": [\n                {\n                    \"query\": {\n                        \"match\": {\n                            \"content\": query\n                        }\n                    }\n                },\n                {\n                    \"query\": {\n                        \"knn\": {\n                            \"field\": \"embedding\",\n                            \"query_vector\": query_embedding,\n                            \"k\": window_size,\n                            \"num_candidates\": window_size * 2\n                        }\n                    }\n                }\n            ],\n            \"rank\": {\n                \"rrf\": {\n                    \"window_size\": window_size,\n                    \"rank_constant\": 60\n                }\n            }\n        }\n\n        response = self.es.search(index=self.index_name, body=search_body)\n\n        return [\n            {\n                \"id\": hit[\"_id\"],\n                \"content\": hit[\"_source\"][\"content\"],\n                \"score\": hit[\"_score\"]\n            }\n            for hit in response[\"hits\"][\"hits\"]\n        ]\n```\n\n### Template 4: Custom Hybrid RAG Pipeline\n\n```python\nfrom typing import List, Dict, Optional, Callable\nfrom dataclasses import dataclass\n\n@dataclass\nclass SearchResult:\n    id: str\n    content: str\n    score: float\n    source: str  # \"vector\", \"keyword\", \"hybrid\"\n    metadata: Dict = None\n\n\nclass HybridRAGPipeline:\n    \"\"\"Complete hybrid search pipeline for RAG.\"\"\"\n\n    def __init__(\n        self,\n        vector_store,\n        keyword_store,\n        embedder,\n        reranker=None,\n        fusion_method: str = \"rrf\",\n        vector_weight: float = 0.5\n    ):\n        self.vector_store = vector_store\n        self.keyword_store = keyword_store\n        self.embedder = embedder\n        self.reranker = reranker\n        self.fusion_method = fusion_method\n        self.vector_weight = vector_weight\n\n    async def search(\n        self,\n        query: str,\n        top_k: int = 10,\n        filter: Optional[Dict] = None,\n        use_rerank: bool = True\n    ) -> List[SearchResult]:\n        \"\"\"Execute hybrid search pipeline.\"\"\"\n\n        # Step 1: Get query embedding\n        query_embedding = self.embedder.embed(query)\n\n        # Step 2: Execute parallel searches\n        vector_results, keyword_results = await asyncio.gather(\n            self._vector_search(query_embedding, top_k * 3, filter),\n            self._keyword_search(query, top_k * 3, filter)\n        )\n\n        # Step 3: Fuse results\n        if self.fusion_method == \"rrf\":\n            fused = self._rrf_fusion(vector_results, keyword_results)\n        else:\n            fused = self._linear_fusion(vector_results, keyword_results)\n\n        # Step 4: Rerank if enabled\n        if use_rerank and self.reranker:\n            fused = await self._rerank(query, fused[:top_k * 2])\n\n        return fused[:top_k]\n\n    async def _vector_search(\n        self,\n        embedding: List[float],\n        limit: int,\n        filter: Dict\n    ) -> List[SearchResult]:\n        results = await self.vector_store.search(embedding, limit, filter)\n        return [\n            SearchResult(\n                id=r[\"id\"],\n                content=r[\"content\"],\n                score=r[\"score\"],\n                source=\"vector\",\n                metadata=r.get(\"metadata\")\n            )\n            for r in results\n        ]\n\n    async def _keyword_search(\n        self,\n        query: str,\n        limit: int,\n        filter: Dict\n    ) -> List[SearchResult]:\n        results = await self.keyword_store.search(query, limit, filter)\n        return [\n            SearchResult(\n                id=r[\"id\"],\n                content=r[\"content\"],\n                score=r[\"score\"],\n                source=\"keyword\",\n                metadata=r.get(\"metadata\")\n            )\n            for r in results\n        ]\n\n    def _rrf_fusion(\n        self,\n        vector_results: List[SearchResult],\n        keyword_results: List[SearchResult]\n    ) -> List[SearchResult]:\n        \"\"\"Fuse with RRF.\"\"\"\n        k = 60\n        scores = {}\n        content_map = {}\n\n        for rank, result in enumerate(vector_results):\n            scores[result.id] = scores.get(result.id, 0) + 1 \u002F (k + rank + 1)\n            content_map[result.id] = result\n\n        for rank, result in enumerate(keyword_results):\n            scores[result.id] = scores.get(result.id, 0) + 1 \u002F (k + rank + 1)\n            if result.id not in content_map:\n                content_map[result.id] = result\n\n        sorted_ids = sorted(scores.keys(), key=lambda x: scores[x], reverse=True)\n\n        return [\n            SearchResult(\n                id=doc_id,\n                content=content_map[doc_id].content,\n                score=scores[doc_id],\n                source=\"hybrid\",\n                metadata=content_map[doc_id].metadata\n            )\n            for doc_id in sorted_ids\n        ]\n\n    async def _rerank(\n        self,\n        query: str,\n        results: List[SearchResult]\n    ) -> List[SearchResult]:\n        \"\"\"Rerank with cross-encoder.\"\"\"\n        if not results:\n            return results\n\n        pairs = [(query, r.content) for r in results]\n        scores = self.reranker.predict(pairs)\n\n        for result, score in zip(results, scores):\n            result.score = float(score)\n\n        return sorted(results, key=lambda x: x.score, reverse=True)\n```\n\n## Best Practices\n\n### Do's\n- **Tune weights empirically** - Test on your data\n- **Use RRF for simplicity** - Works well without tuning\n- **Add reranking** - Significant quality improvement\n- **Log both scores** - Helps with debugging\n- **A\u002FB test** - Measure real user impact\n\n### Don'ts\n- **Don't assume one size fits all** - Different queries need different weights\n- **Don't skip keyword search** - Handles exact matches better\n- **Don't over-fetch** - Balance recall vs latency\n- **Don't ignore edge cases** - Empty results, single word queries\n\n## Resources\n\n- [RRF Paper](https:\u002F\u002Fplg.uwaterloo.ca\u002F~gvcormac\u002Fcormacksigir09-rrf.pdf)\n- [Vespa Hybrid Search](https:\u002F\u002Fblog.vespa.ai\u002Fimproving-text-ranking-with-few-shot-prompting\u002F)\n- [Cohere Rerank](https:\u002F\u002Fdocs.cohere.com\u002Fdocs\u002Freranking)\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-external_plugins\u002Fllm-application-dev\u002Fskills\u002Fhybrid-search-implementation",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill hybrid-search-implementation",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill hybrid-search-implementation",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill hybrid-search-implementation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-external_plugins\u002Fllm-application-dev\u002Fskills\u002Fhybrid-search-implementation\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]