test_aggregation_api.py 5.47 KB
#!/usr/bin/env python3
"""
Test script for aggregation functionality
"""

import requests
import json

API_BASE_URL = 'http://120.76.41.98:6002'

def test_search_with_aggregations():
    """Test search with aggregations"""

    # Test data
    test_query = {
        "query": "玩具",
        "size": 5,
        "aggregations": {
            "category_stats": {
                "terms": {
                    "field": "categoryName_keyword",
                    "size": 10
                }
            },
            "brand_stats": {
                "terms": {
                    "field": "brandName_keyword",
                    "size": 10
                }
            },
            "price_ranges": {
                "range": {
                    "field": "price",
                    "ranges": [
                        {"key": "0-50", "to": 50},
                        {"key": "50-100", "from": 50, "to": 100},
                        {"key": "100-200", "from": 100, "to": 200},
                        {"key": "200+", "from": 200}
                    ]
                }
            }
        }
    }

    print("Testing search with aggregations...")
    print(f"Query: {json.dumps(test_query, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(f"{API_BASE_URL}/search/",
                               json=test_query,
                               headers={'Content-Type': 'application/json'})

        print(f"Status Code: {response.status_code}")

        if response.ok:
            data = response.json()
            print(f"Found {data['total']} results in {data['took_ms']}ms")
            print(f"Max Score: {data['max_score']}")

            # Print aggregations
            if data.get('aggregations'):
                print("\nAggregations:")
                for agg_name, agg_result in data['aggregations'].items():
                    print(f"\n{agg_name}:")
                    if 'buckets' in agg_result:
                        for bucket in agg_result['buckets'][:5]:  # Show first 5 buckets
                            print(f"  - {bucket['key']}: {bucket['doc_count']}")

            # Print first few results
            print(f"\nFirst 3 results:")
            for i, hit in enumerate(data['hits'][:3]):
                source = hit['_source']
                print(f"\n{i+1}. {source.get('name', 'N/A')}")
                print(f"   Category: {source.get('categoryName', 'N/A')}")
                print(f"   Brand: {source.get('brandName', 'N/A')}")
                print(f"   Price: {source.get('price', 'N/A')}")
                print(f"   Score: {hit['_score']:.4f}")
        else:
            print(f"Error: {response.status_code}")
            print(f"Response: {response.text}")

    except Exception as e:
        print(f"Request failed: {e}")

def test_search_with_filters():
    """Test search with filters"""

    test_filters = {
        "query": "玩具",
        "size": 5,
        "filters": {
            "categoryName_keyword": ["玩具"],
            "price_ranges": ["0-50", "50-100"]
        }
    }

    print("\n\nTesting search with filters...")
    print(f"Query: {json.dumps(test_filters, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(f"{API_BASE_URL}/search/",
                               json=test_filters,
                               headers={'Content-Type': 'application/json'})

        print(f"Status Code: {response.status_code}")

        if response.ok:
            data = response.json()
            print(f"Found {data['total']} results in {data['took_ms']}ms")

            print(f"\nFirst 3 results:")
            for i, hit in enumerate(data['hits'][:3]):
                source = hit['_source']
                print(f"\n{i+1}. {source.get('name', 'N/A')}")
                print(f"   Category: {source.get('categoryName', 'N/A')}")
                print(f"   Brand: {source.get('brandName', 'N/A')}")
                print(f"   Price: {source.get('price', 'N/A')}")
                print(f"   Score: {hit['_score']:.4f}")
        else:
            print(f"Error: {response.status_code}")
            print(f"Response: {response.text}")

    except Exception as e:
        print(f"Request failed: {e}")

def test_search_with_sorting():
    """Test search with sorting"""

    test_sort = {
        "query": "玩具",
        "size": 5,
        "sort_by": "price",
        "sort_order": "asc"
    }

    print("\n\nTesting search with sorting (price ascending)...")
    print(f"Query: {json.dumps(test_sort, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(f"{API_BASE_URL}/search/",
                               json=test_sort,
                               headers={'Content-Type': 'application/json'})

        print(f"Status Code: {response.status_code}")

        if response.ok:
            data = response.json()
            print(f"Found {data['total']} results in {data['took_ms']}ms")

            print(f"\nFirst 3 results (sorted by price):")
            for i, hit in enumerate(data['hits'][:3]):
                source = hit['_source']
                print(f"\n{i+1}. {source.get('name', 'N/A')}")
                print(f"   Price: {source.get('price', 'N/A')}")
                print(f"   Score: {hit['_score']:.4f}")
        else:
            print(f"Error: {response.status_code}")
            print(f"Response: {response.text}")

    except Exception as e:
        print(f"Request failed: {e}")

if __name__ == "__main__":
    test_search_with_aggregations()
    test_search_with_filters()
    test_search_with_sorting()