> ## Documentation Index
> Fetch the complete documentation index at: https://docs.insecureweb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Property Values with Count API

> Get unique values for alert properties along with their occurrence counts for analytics and filtering purposes.

## Overview

This endpoint returns unique values for a specified alert property (field) along with the count of how many times each value appears. It's useful for creating filter dropdowns, analytics dashboards, and understanding data distribution in your alerts.

<Note>
  **Authorization Required:** Include a valid Bearer Token in the Authorization header.
</Note>

***

## Endpoint Details

<Card title="POST /api/elasticsearch/property/values-with-count" icon="chart-bar">
  **Method:** POST\
  **Content-Type:** application/json\
  **Authentication:** Bearer Token required\
  **Response:** Array of value/count objects
</Card>

***

## Request Body

<ParamField body="field" type="string" required>
  The alert property field to analyze (e.g., "status", "severity", "dataSource")
</ParamField>

<ParamField body="filters" type="array">
  Optional filters to apply before analyzing the field values
</ParamField>

<ParamField body="index" type="string" required>
  Elasticsearch index pattern to search (typically "alert-\*")
</ParamField>

<ParamField body="top" type="integer" default="10">
  Maximum number of unique values to return
</ParamField>

<ParamField body="orderByCount" type="boolean" default="true">
  Whether to order results by count (true) or alphabetically (false)
</ParamField>

<ParamField body="sortAsc" type="boolean" default="false">
  Sort order: true for ascending, false for descending
</ParamField>

***

## JSON Schema

```json theme={null}
{
  "type": "object",
  "properties": {
    "field": {
      "type": "string",
      "description": "Field name to analyze"
    },
    "filters": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "field": { "type": "string" },
          "operator": { "type": "string" },
          "value": { "oneOf": [{"type": "string"}, {"type": "integer"}, {"type": "array"}] }
        }
      },
      "description": "Optional filters to apply"
    },
    "index": {
      "type": "string",
      "description": "Elasticsearch index pattern"
    },
    "top": {
      "type": "integer",
      "description": "Maximum number of results"
    },
    "orderByCount": {
      "type": "boolean",
      "description": "Order by count vs alphabetical"
    },
    "sortAsc": {
      "type": "boolean",
      "description": "Sort direction"
    }
  },
  "required": ["field", "index"]
}
```

***

## Request & Response Examples

<RequestExample>
  ```bash Request theme={null}
  curl -X POST "https://demo.utmstack.com/api/elasticsearch/property/values-with-count" \
    -H "Authorization: Bearer <your_access_token>" \
    -H "Content-Type: application/json" \
    -d '{
      "field": "severity",
      "filters": [
        {
          "field": "@timestamp",
          "operator": "IS_BETWEEN",
          "value": ["now-7d", "now"]
        }
      ],
      "index": "alert-*",
      "top": 10,
      "orderByCount": true,
      "sortAsc": false
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  [
    {
      "value": "2",
      "count": 156
    },
    {
      "value": "3", 
      "count": 89
    },
    {
      "value": "1",
      "count": 45
    },
    {
      "value": "4",
      "count": 23
    },
    {
      "value": "5",
      "count": 8
    }
  ]
  ```
</ResponseExample>

### Additional Code Examples

<CodeGroup>
  ```javascript Node.js theme={null}
  import axios from "axios";

  const getPropertyValuesWithCount = async (field, options = {}) => {
    const token = "<your_access_token>";
    
    const payload = {
      field: field,
      filters: options.filters || [],
      index: options.index || "alert-*",
      top: options.top || 10,
      orderByCount: options.orderByCount !== false,
      sortAsc: options.sortAsc || false
    };

    try {
      const response = await axios.post(
        "https://demo.utmstack.com/api/elasticsearch/property/values-with-count",
        payload,
        {
          headers: { 
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        }
      );
      
      console.log(`Top ${field} values:`, response.data);
      return response.data;
    } catch (error) {
      console.error("Error getting property values:", error.response?.data || error.message);
    }
  };

  // Usage examples
  await getPropertyValuesWithCount("severity");
  await getPropertyValuesWithCount("dataSource", { top: 20 });
  ```

  ```python Python theme={null}
  import requests

  def get_property_values_with_count(field, filters=None, index="alert-*", top=10, order_by_count=True, sort_asc=False):
      url = "https://demo.utmstack.com/api/elasticsearch/property/values-with-count"
      
      payload = {
          "field": field,
          "filters": filters or [],
          "index": index,
          "top": top,
          "orderByCount": order_by_count,
          "sortAsc": sort_asc
      }
      
      headers = {
          "Authorization": "Bearer <your_access_token>",
          "Content-Type": "application/json"
      }
      
      response = requests.post(url, json=payload, headers=headers)
      
      if response.status_code == 200:
          data = response.json()
          print(f"Top {field} values:")
          for item in data:
              print(f"  {item['value']}: {item['count']} occurrences")
          return data
      else:
          print(f"Error: {response.status_code} - {response.text}")
      
      return None

  # Usage examples
  get_property_values_with_count("severity")
  get_property_values_with_count("status", filters=[
      {"field": "@timestamp", "operator": "IS_BETWEEN", "value": ["now-24h", "now"]}
  ])
  ```
</CodeGroup>

***

## Response Details

### Successful Response

<Tabs>
  <Tab title="Severity Analysis">
    ```json theme={null}
    [
      {"value": "3", "count": 156},
      {"value": "2", "count": 89},
      {"value": "4", "count": 45},
      {"value": "1", "count": 23},
      {"value": "5", "count": 8}
    ]
    ```
  </Tab>

  <Tab title="Data Source Analysis">
    ```json theme={null}
    [
      {"value": "windows-server-01", "count": 234},
      {"value": "firewall-main", "count": 178},
      {"value": "web-server-prod", "count": 92},
      {"value": "database-cluster", "count": 56}
    ]
    ```
  </Tab>

  <Tab title="Empty Result">
    ```json theme={null}
    []
    ```
  </Tab>
</Tabs>

***

## Status Codes

<ResponseField name="200" type="OK">
  Successfully retrieved property values and counts
</ResponseField>

<ResponseField name="400" type="Bad Request">
  Invalid field name, malformed filters, or invalid parameters
</ResponseField>

<ResponseField name="401" type="Unauthorized">
  Missing or invalid Bearer token
</ResponseField>

<ResponseField name="500" type="Internal Server Error">
  Internal server error during analysis
</ResponseField>

***

## Common Use Cases

### Filter Dropdown Population

```javascript theme={null}
// Populate severity filter dropdown
const populateSeverityFilter = async () => {
  const severityValues = await getPropertyValuesWithCount("severity");
  const dropdown = document.getElementById("severity-filter");
  
  dropdown.innerHTML = '<option value="">All Severities</option>';
  
  severityValues.forEach(item => {
    const option = document.createElement("option");
    option.value = item.value;
    option.textContent = `Severity ${item.value} (${item.count})`;
    dropdown.appendChild(option);
  });
};
```

### Analytics Dashboard

```javascript theme={null}
// Create pie chart data for alert distribution
const createAlertDistributionChart = async () => {
  const statusData = await getPropertyValuesWithCount("status", {
    filters: [
      {
        field: "@timestamp",
        operator: "IS_BETWEEN", 
        value: ["now-30d", "now"]
      }
    ]
  });
  
  const chartData = {
    labels: statusData.map(item => `Status ${item.value}`),
    datasets: [{
      data: statusData.map(item => item.count),
      backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0']
    }]
  };
  
  // Use with Chart.js or similar library
  new Chart(ctx, {
    type: 'pie',
    data: chartData
  });
};
```

### Top Offenders Report

```python theme={null}
def generate_top_offenders_report():
    """Generate report of top sources generating alerts"""
    
    # Get top data sources
    sources = get_property_values_with_count(
        field="dataSource",
        filters=[
            {"field": "@timestamp", "operator": "IS_BETWEEN", "value": ["now-7d", "now"]},
            {"field": "status", "operator": "IS_NOT", "value": 5}  # Exclude completed
        ],
        top=20
    )
    
    print("Top Alert Sources (Last 7 Days):")
    print("=" * 50)
    
    for i, source in enumerate(sources, 1):
        percentage = (source['count'] / sum(s['count'] for s in sources)) * 100
        print(f"{i:2d}. {source['value']:<30} {source['count']:>6} alerts ({percentage:.1f}%)")
    
    return sources
```

***

## Advanced Filtering Examples

### Time-based Analysis

```json theme={null}
{
  "field": "severity",
  "filters": [
    {
      "field": "@timestamp",
      "operator": "IS_BETWEEN",
      "value": ["now-24h", "now"]
    },
    {
      "field": "status",
      "operator": "IS_IN",
      "value": [2, 3]
    }
  ],
  "index": "alert-*",
  "top": 5,
  "orderByCount": true,
  "sortAsc": false
}
```

### Exclude False Positives

```json theme={null}
{
  "field": "dataSource",
  "filters": [
    {
      "field": "tags",
      "operator": "IS_NOT",
      "value": "False positive"
    },
    {
      "field": "severity",
      "operator": "GREATER_EQUAL",
      "value": 3
    }
  ],
  "index": "alert-*",
  "top": 15,
  "orderByCount": true,
  "sortAsc": false
}
```

### Category Analysis

```json theme={null}
{
  "field": "category",
  "filters": [
    {
      "field": "@timestamp",
      "operator": "IS_BETWEEN",
      "value": ["now-30d", "now"]
    }
  ],
  "index": "alert-*",
  "top": 25,
  "orderByCount": true,
  "sortAsc": false
}
```

***

## Performance Considerations

<Warning>
  **Performance Tips:**

  * Use appropriate `top` limits to avoid large result sets
  * Apply filters to reduce the data set being analyzed
  * Consider caching results for frequently requested fields
  * Use specific time ranges rather than analyzing all historical data
  * Monitor query performance for fields with high cardinality
</Warning>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Field Selection">
    **Commonly analyzed fields:**

    * `severity` - Alert severity levels
    * `status` - Alert status distribution
    * `dataSource` - Top alert sources
    * `category` - Alert categories
    * `tactic` - MITRE ATT\&CK tactics
    * `tags` - Applied tags
  </Accordion>

  <Accordion title="Filter Strategy">
    **Effective filtering:**

    * Always include time filters to limit scope
    * Exclude false positives for meaningful analysis
    * Filter by status to focus on actionable alerts
    * Use severity filters for priority analysis
  </Accordion>

  <Accordion title="Result Limits">
    **Appropriate limits:**

    * Dropdowns: 10-20 items
    * Dashboard charts: 5-15 items
    * Reports: 20-50 items
    * Avoid requesting more than 100 items
  </Accordion>
</AccordionGroup>

***

## OpenAPI Specification

```yaml theme={null}
post:
  summary: "Get property values with occurrence counts"
  tags:
    - Alert Analytics
  security:
    - bearerAuth: []
  requestBody:
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/PropertyValuesWithCountRequest'
  responses:
    '200':
      description: "List of property values with counts"
      content:
        application/json:
          schema:
            type: array
            items:
              type: object
              properties:
                value:
                  type: string
                  description: "The property value"
                count:
                  type: integer
                  description: "Number of occurrences"
    '400':
      description: "Invalid request parameters"
    '401':
      description: "Unauthorized"
    '500':
      description: "Internal server error"

components:
  schemas:
    PropertyValuesWithCountRequest:
      type: object
      required:
        - field
        - index
      properties:
        field:
          type: string
          description: "Field name to analyze"
        filters:
          type: array
          items:
            $ref: '#/components/schemas/FilterType'
          description: "Optional filters to apply"
        index:
          type: string
          description: "Elasticsearch index pattern"
        top:
          type: integer
          default: 10
          description: "Maximum number of results"
        orderByCount:
          type: boolean
          default: true
          description: "Order by count vs alphabetical"
        sortAsc:
          type: boolean
          default: false
          description: "Sort direction"
```
