# Labeled Meta Property Graphs (LMPG): A Property-Centric Approach to Graph Database Architecture

> Discover how LMPG transforms graph databases by treating properties as first-class citizens rather than simple node attributes. This comprehensive technical guide explores RushDB's groundbreaking architecture that enables automatic schema evolution, property-first queries, and cross-domain analytics impossible in traditional property graphs or RDF systems.

Canonical URL: https://rushdb.com/blog/labeled-meta-property-graphs-rushdb-s-revolutionary-approach-to-graph-database-architecture
Published: 2025-07-07T16:05:51.196Z
Updated: 2025-07-10T16:50:57.683Z

In the evolving landscape of database technologies, graph databases have emerged as powerful solutions for managing interconnected data. However, most graph databases still require developers to think in terms of nodes, edges, and complex query languages. RushDB introduces a paradigm shift with its **Labeled Meta Property Graph (LMPG)** architecture – a revolutionary approach that makes properties first-class citizens and enables unprecedented flexibility in data modeling and querying.

What sets LMPG apart is its **unified query interface** that allows a single Data Transfer Object (DTO) to query Records, Labels, Properties, Relationships, and Available Values across any subgraph perspective. This creates what we call "database self-awareness" – the ability for the system to introspect and optimize queries dynamically based on the property-centric architecture.

## The Problem with Traditional Graph Approaches

Traditional property graphs, while powerful, force developers into rigid thinking patterns:

- **Schema-first mindset**: You must define your data structure before storing data
- **Query complexity**: Learning Cypher, Gremlin, or other graph query languages
- **Relationship overhead**: Manually defining and maintaining relationships
- **Type constraints**: Rigid type systems that don't adapt to evolving data

Consider a typical e-commerce scenario in a traditional property graph:

```cypher
// Traditional approach - you must know the schema
MATCH (product:Product)-[:BELONGS_TO]->(category:Category)
WHERE product.price > 100 AND category.name = 'Electronics'
RETURN product.name, product.price
```

This requires understanding:
- Node labels (Product, Category)
- Relationship types (BELONGS_TO)
- Property names and their locations
- Query syntax

## Introducing Labeled Meta Property Graphs (LMPG)

RushDB's LMPG architecture flips this model on its head by making **properties** the central organizing principle. In LMPG:

1. **Properties are first-class citizens** with their own nodes
2. **Records are connected through shared properties**
3. **Relationships emerge automatically** based on property overlap
4. **Types are inferred and maintained automatically**

### The LMPG Structure

```mermaid
graph LR
    subgraph "Properties (First-Class Citizens)"
        P1[":Property<br/>name: 'price'<br/>type: 'number'"]
        P2[":Property<br/>name: 'color'<br/>type: 'string'"]
        P3[":Property<br/>name: 'brand'<br/>type: 'string'"]
    end

    subgraph "Records (Data Containers)"
        R1[":Record :Car<br/>price: 25000<br/>color: 'red'<br/>brand: 'Toyota'"]
        R2[":Record :House<br/>price: 350000<br/>color: 'white'"]
        R3[":Record :Shirt<br/>color: 'blue'<br/>brand: 'Nike'"]
    end

    P1 -->|__RUSHDB__RELATION__VALUE__| R1
    P1 -->|__RUSHDB__RELATION__VALUE__| R2
    P2 -->|__RUSHDB__RELATION__VALUE__| R1
    P2 -->|__RUSHDB__RELATION__VALUE__| R2
    P2 -->|__RUSHDB__RELATION__VALUE__| R3
    P3 -->|__RUSHDB__RELATION__VALUE__| R1
    P3 -->|__RUSHDB__RELATION__VALUE__| R3
```

## From JSON to LMPG: The BFS Transformation

RushDB employs a sophisticated **Breadth-First Search (BFS)** algorithm to automatically convert hierarchical JSON data into LMPG structures. This process eliminates the need for manual schema design while preserving data relationships.

### Example: E-commerce Product Data

Let's see how RushDB transforms complex JSON into an LMPG:

**Input JSON:**
```json
{
  "products": [
    {
      "id": "prod-001",
      "name": "Wireless Headphones",
      "price": 299.99,
      "inStock": true,
      "category": {
        "name": "Electronics",
        "department": "Audio"
      },
      "specifications": {
        "batteryLife": "30 hours",
        "connectivity": ["Bluetooth 5.0", "USB-C"],
        "weight": 250
      },
      "reviews": [
        {
          "rating": 5,
          "comment": "Excellent sound quality",
          "verified": true
        },
        {
          "rating": 4,
          "comment": "Good value for money",
          "verified": false
        }
      ]
    }
  ]
}
```

**LMPG Transformation Process:**

1. **BFS Level 0** - Root object detection
2. **BFS Level 1** - Extract main entities (product, category, specifications)
3. **BFS Level 2** - Process nested objects and arrays
4. **BFS Level 3** - Handle deeply nested structures (reviews)

**Resulting Graph Structure:**

```mermaid
graph LR
    subgraph "Property Nodes"
        PN[":Property name:string"]
        PP[":Property price:number"]
        PS[":Property inStock:boolean"]
        PR[":Property rating:number"]
        PC[":Property comment:string"]
        PV[":Property verified:boolean"]
        PB[":Property batteryLife:string"]
        PW[":Property weight:number"]
        PD[":Property department:string"]
    end

    subgraph "Record Nodes"
        R1[":Record :Product<br/>id: prod-001<br/>name: Wireless Headphones<br/>price: 299.99<br/>inStock: true"]
        R2[":Record :Category<br/>name: Electronics<br/>department: Audio"]
        R3[":Record :Specifications<br/>batteryLife: 30 hours<br/>weight: 250"]
        R4[":Record :Review<br/>rating: 5<br/>comment: Excellent...<br/>verified: true"]
        R5[":Record :Review<br/>rating: 4<br/>comment: Good value...<br/>verified: false"]
    end

    PN -->|__RUSHDB__RELATION__VALUE__| R1
    PN -->|__RUSHDB__RELATION__VALUE__| R2
    PP -->|__RUSHDB__RELATION__VALUE__| R1
    PS -->|__RUSHDB__RELATION__VALUE__| R1
    PR -->|__RUSHDB__RELATION__VALUE__| R4
    PR -->|__RUSHDB__RELATION__VALUE__| R5
    PC -->|__RUSHDB__RELATION__VALUE__| R4
    PC -->|__RUSHDB__RELATION__VALUE__| R5
    PV -->|__RUSHDB__RELATION__VALUE__| R4
    PV -->|__RUSHDB__RELATION__VALUE__| R5
    PB -->|__RUSHDB__RELATION__VALUE__| R3
    PW -->|__RUSHDB__RELATION__VALUE__| R3
    PD -->|__RUSHDB__RELATION__VALUE__| R2

    R1 -.->|HAS_CATEGORY| R2
    R1 -.->|HAS_SPECIFICATIONS| R3
    R1 -.->|HAS_REVIEW| R4
    R1 -.->|HAS_REVIEW| R5
```

### Auto-Generated Internal Structure

RushDB automatically enhances each record with metadata:

```javascript
// RushDB's representation (simplified)
{
  "__id": "01968aa4-22c1-781a-8e8c-8fe6be6c3fd4", // UUIDv7
  "__label": "Product",                           // Auto-derived label
  "__proptypes": {                                // Type metadata
    "name": "string",
    "price": "number",
    "inStock": "boolean"
  },
  "name": "Wireless Headphones",
  "price": 299.99,
  "inStock": true
}
```

## LMPG vs Other Graph Paradigms

### Comparison Matrix

| Feature | Traditional Property Graph | RDF/Triple Store | Knowledge Graph | LMPG (RushDB) |
|---------|---------------------------|------------------|-----------------|---------------|
| **Schema Requirements** | Rigid, predefined | Ontology-based | Schema-on-write | Schema-free |
| **Query Complexity** | High (Cypher/Gremlin) | Very High (SPARQL) | Medium | Low (JSON queries) |
| **Property Handling** | Node attributes | Triple predicates | Entity properties | First-class citizens |
| **Cross-type Queries** | Complex joins | SPARQL UNION | Limited | Native support |
| **Data Import** | Manual modeling | RDF conversion | ETL pipelines | Auto-normalization |
| **Learning Curve** | Steep | Very Steep | Moderate | Minimal |

### Traditional Property Graph Approach

```cypher
// Find all items with price > 1000 across different types
MATCH (n)
WHERE (n:Car OR n:House OR n:Jewelry)
  AND n.price > 1000
RETURN n.name, n.price, labels(n)
```

**Problems:**
- Must know all possible labels
- Cannot discover new types automatically
- Requires complex OR conditions
- Brittle when new types are added

### LMPG Approach

```sdk
# Same query in RushDB - discover ANY record with price > 1000

from rushdb import RushDB

db = RushDB("RUSHDB_API_TOKEN")

results = db.records.find({
    "where": {
        "price": { "$gt": 1000 }
    }
})
___SPLIT___
// Same query in RushDB - discover ANY record with price > 1000

import RushDB from '@rushdb/javascript-sdk';

const db = new RushDB('RUSHDB_API_TOKEN');

const results = await db.records.find({
  where: {
    price: { $gt: 1000 }
  }
});
```

**Advantages:**
- Automatically finds all records regardless of type
- No need to know labels in advance
- Discovers relationships through shared properties
- Self-adapting to new data types

## Cross-Domain Insights Through Property Traversal

One of LMPG's most powerful features is its ability to reveal hidden connections across seemingly unrelated data through property-based traversal.

### Example: Multi-Domain Analysis

Consider data from different domains stored in the same RushDB instance:

```json
// E-commerce products
{
  "label": "Product",
  "name": "Premium Coffee Maker",
  "price": 299,
  "color": "stainless steel",
  "rating": 4.8
}

// Real estate listings
{
  "label": "Property",
  "address": "123 Main St",
  "price": 299000,
  "color": "white",
  "rating": 4.2
}

// Restaurant reviews
{
  "label": "Restaurant",
  "name": "Downtown Bistro",
  "rating": 4.8,
  "color": "modern"
}

// Investment portfolios
{
  "label": "Stock",
  "symbol": "AAPL",
  "price": 299.50,
  "rating": 4.5
}
```

### Property-Based Cross-Domain Queries

**1. Find all highly-rated items regardless of domain:**
```sdk
results = db.records.find({
    "where": {
        "rating": { "$gte":  4.5 }
    }
})
# Returns: Coffee Maker, Restaurant, Stock
___SPLIT___
const results = await db.records.find({
  where: {
    rating: { $gte: 4.5 }
  }
});
// Returns: Coffee Maker, Restaurant, Stock
```

**2. Price range analysis across all domains:**
```sdk
results = db.records.find({
    "where": {
        "price": { "$gte": 250, "$lte": 350 }
    }
})
# Returns: Coffee Maker, Stock, and potentially Real Estate down payments
___SPLIT___
const results = await db.records.find({
  where: {
    price: { $gte: 250, $lte: 350 }
  }
});
// Returns: Coffee Maker, Stock, and potentially Real Estate down payments
```

**3. Color-based aesthetic preferences:**
```sdk
results = db.records.find({
    "where": {
         "color": { "$in": ["stainless steel", "modern", "white"] }
    }
})
# Reveals design preferences across products, properties, and venues
___SPLIT___
const results = await db.records.find({
  where: {
    color: { $in: ["stainless steel", "modern", "white"] }
  }
});
// Reveals design preferences across products, properties, and venues
```

## Advanced LMPG Querying Patterns

### Property Intersection Analysis

```mermaid
graph LR
    subgraph "Shared Properties Create Insights"
        P1[":Property rating:number"]
        P2[":Property price:number"]
    end

    subgraph "Cross-Domain Records"
        R1[":Restaurant<br/>rating: 4.8"]
        R2[":Product<br/>rating: 4.8<br/>price: 299"]
        R3[":Hotel<br/>rating: 4.2<br/>price: 150"]
        R4[":Stock<br/>price: 299"]
    end

    P1 --> R1
    P1 --> R2
    P1 --> R3
    P2 --> R2
    P2 --> R3
    P2 --> R4
```

### Multi-Property Queries

```sdk
# Find premium experiences (high rating + reasonable price)
results = db.records.find({
    "where": {
        "rating": { "$gte": 4.5 },
        "price": { "$lte": 500 }
    }
})
___SPLIT___
// Find premium experiences (high rating + reasonable price)
const results = await db.records.find({
  where: {
    rating: { $gte: 4.5 },
    price: { $lte: 500 }
  }
});
```

**Response structure:**
```javascript
{
  "data": [
    { "__label": "Restaurant", "name": "Downtown Bistro", "rating": 4.8, "price": 45 },
    { "__label": "Product", "name": "Coffee Maker", "rating": 4.8, "price": 299 },
    { "__label": "Hotel", "name": "Boutique Inn", "rating": 4.6, "price": 180 }
  ]
}
```

## Vector Integration in LMPG

RushDB's LMPG architecture seamlessly integrates vector operations as first-class properties, enabling AI-powered insights while maintaining the unified query interface:

### Vector Properties as First-Class Citizens

```sdk
# Add vector embeddings as properties
db.records.create({
    "label": "Document",
    "data": {
        "title": "AI Research Paper",
        "content": "Large language models have revolutionized...",
        "embedding": [0.1, 0.8, -0.3, 0.9, ...], # 1536-dimensional vector
        "category": "AI Research",
        "publishDate": "2024-01-15",
        "citationCount": 42,
        "impact_score": 8.7
    }
});
___SPLIT___
// Add vector embeddings as properties
await db.records.create({
  label: "Document",
  data: {
    title: "AI Research Paper",
    content: "Large language models have revolutionized...",
    embedding: [0.1, 0.8, -0.3, 0.9, ...], // 1536-dimensional vector
    category: "AI Research",
    publishDate: "2024-01-15",
    citationCount: 42,
    impact_score: 8.7
  }
});
```

### Hybrid Search with Unified Querying

The power of LMPG shows in combining semantic similarity with structured property filters:

```sdk
# Vector similarity search combined with property filtering
similarDocuments = db.records.find({
    "where": {
        "category": "AI Research",
        "publishDate": { "$gte": "2024-01-01" },
        "citationCount": { "$gte": 10 },
        "embedding": {
            "$vector": {
                "fn": "gds.similarity.cosine",
                "query": queryEmbedding,
                "threshold": 0.75  # Interpreted as $gte: 0.75
            }
        }
    },
    "limit": 10
})
___SPLIT___
// Vector similarity search combined with property filtering
const similarDocuments = await db.records.find({
  where: {
    category: "AI Research",
    publishDate: { $gte: "2024-01-01" },
    citationCount: { $gte: 10 },
    embedding: {
      $vector: {
        fn: "gds.similarity.cosine",
        query: queryEmbedding,
        threshold: 0.75  // Interpreted as $gte: 0.75
      }
    }
  },
  limit: 10
});
```

### Multi-Perspective Vector Analysis

The same query provides vector insights across all perspectives:

**Records Perspective:**
```javascript
// Documents with semantic similarity + structured filters
{
  "data": [
    {
      "__id": "...",
      "title": "Transformer Architectures in NLP",
      "embedding": [...],
      "similarity_score": 0.89,
      "__label": "Document"
    }
  ]
}
```

**Properties Perspective:**
```javascript
// Discovers vector properties automatically
{
  "data": [
    {
      "name": "embedding",
      "type": "vector",
      "dimensions": 1536,
      "similarity_function": "cosine"
    }
  ]
}
```

**Relationships Perspective:**
```javascript
// Vector-based relationships discovered
{
  "data": [
    {
      "sourceId": "doc1",
      "targetId": "doc2",
      "type": "SEMANTIC_SIMILARITY",
      "similarity_score": 0.85
    }
  ]
}
```

### Vector-Enhanced Performance

```mermaid
graph TB
    subgraph "Traditional Vector DB"
        T1[Vector Index] --> T2[Similarity Search]
        T2 --> T3[Post-Filter Results]
        T3 --> T4[Join with Metadata]
    end

    subgraph "LMPG Vector Integration"
        P1[Property-Vector Index] --> P2[Parallel Execution]
        P2 --> P3[Vector Similarity]
        P2 --> P4[Property Filtering]
        P3 --> P5[Unified Results]
        P4 --> P5
    end

    T4 --> TR[Sequential Processing]
    P5 --> PR[Parallel Processing]
```

This enables powerful hybrid search combining semantic similarity with structured property filters, all through the same unified interface.

---

*Learn more about [Vector Search](https://docs.rushdb.com/concepts/search/where#vector-operators)*

## Performance Characteristics

### Why LMPG Scales Differently

Traditional database performance degrades with data size and query complexity. LMPG maintains consistent performance through its revolutionary **perforating query architecture** that skips expensive operations by leveraging properties as dynamic indices.

**1. Property-First Indexing:**
```
Traditional JOIN: O(n × m × log(k))
LMPG Traversal: O(p + r)
```
Where:
- n, m, k = table/node sizes
- p = number of properties
- r = number of relevant records

**2. Perforating Query Execution:**

```mermaid
graph LR
    subgraph "Traditional Database Query Path"
        T1[Table Scan] --> T2[Filter Apply]
        T2 --> T3[Join Execution]
        T3 --> T4[Aggregation]
        T4 --> T5[Sort & Limit]
        T5 --> T6[Result Set]
    end

    subgraph "LMPG Perforating Query Path"
        P1[Property Index] --> P2[Record Pointer]
        P2 --> P3[Lazy Load Relations]
        P3 --> P4[Cached Metadata]
        P4 --> P5[Direct Result]
    end

    T6 --> TR["High Latency<br/>O(n×m×log k)"]
    P5 --> PR["Low Latency<br/>O(p+r)"]
```

**3. Dynamic Index Management:**

Properties act as **living indices** that:
- **Self-organize** with controllable overhead
- **Adapt to data distribution** in real-time

**4. Handful Index Optimization:**
```sql
-- Auto-generated Neo4j indexes for each property
CREATE INDEX property_name_string FOR (n:__RUSHDB__LABEL__PROPERTY__)
ON (n.name, n.type, n.projectId, n.metadata);

CREATE INDEX record_lookup FOR (n:__RUSHDB__LABEL__RECORD__)
ON (n.__RUSHDB__KEY__ID__, n.__RUSHDB__KEY__PROJECT__ID__);
```

## Graph Perforating Architecture: Technical Deep Dive

RushDB's revolutionary **graph perforating architecture** achieves unprecedented data observability through a single unified query interface. Unlike traditional databases that require separate APIs for different data perspectives, LMPG enables one query to simultaneously access Records, Labels, Properties, Values, and Relationships.

### The Unified Query Foundation

Consider this complex organizational analysis query that demonstrates cross-entity traversal with multi-level filtering:

```javascript
// Example: Enterprise Data Intelligence Query
const QUERY = {
    labels: ["DEPARTMENT"],
    where: {
        name: { "$contains": "e" },
        PROJECT: {
            budget: {
                $xor: {
                    $lte: 10000000,
                    $gte: 15000000
                }
            },
            EMPLOYEE: {
                salary: { $gte: 300000 }
            }
        }
    }
}
```

This query structure directly maps to graph traversal paths, enabling intuitive nested querying across related entities without complex join syntax:

```mermaid
graph LR
    subgraph "Query Traversal Path"
        D[":DEPARTMENT<br/>name contains 'e'"]
        P[":PROJECT<br/>budget ≤10M XOR ≥15M"]
        E[":EMPLOYEE<br/>salary ≥300K"]
    end

    D -->|RUSHDB_DEFAULT_RELATION| P
    P -->|RUSHDB_DEFAULT_RELATION| E

    subgraph "Property Filters"
        DF["name: { $contains: 'e' }"]
        PF["budget: { $xor: { $lte: 10M, $gte: 15M } }"]
        EF["salary: { $gte: 300000 }"]
    end

    D -.-> DF
    P -.-> PF
    E -.-> EF
```

### 1. Records Perspective: Data Retrieval

**SDK Call:**
```sdk
# Get actual department records matching criteria
records = db.records.find(QUERY)
___SPLIT___
// Get actual department records matching criteria
const records = await db.records.find(QUERY);
```

**Generated Cypher Query:**
```cypher
MATCH (record:__RUSHDB__LABEL__RECORD__:`DEPARTMENT` { __RUSHDB__KEY__PROJECT__ID__: $projectId })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
WITH record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
RETURN record
SKIP 0 LIMIT 1000
```

**Resulting Data:**
```json
{
  "data": [
    {
      "__id": "01974151-41f4-7c7e-a9bd-a28df7703077",
      "__label": "DEPARTMENT",
      "name": "Research and Development",
      "description": "Innovation-focused department driving product evolution",
      "headcount": 150,
      "budget": 2500000
    }
  ],
  "total": 5,
  "success": true
}
```

### 2. Labels Perspective: Entity Type Discovery

**SDK Call:**
```sdk
# Discover all entity types matching the criteria
labels = db.labels.find(QUERY)
___SPLIT___
// Discover all entity types matching the criteria
const labels = await db.labels.find(QUERY);
```

**Generated Cypher Query:**
```cypher
MATCH (record:__RUSHDB__LABEL__RECORD__ { __RUSHDB__KEY__PROJECT__ID__: $projectId })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
WITH record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
WITH DISTINCT record, [label IN labels(record) WHERE label <> "__RUSHDB__LABEL__RECORD__"] as recordLabels
RETURN count(recordLabels) as total, recordLabels[0] as label
```

**Resulting Data:**
```json
{
  "data": {
    "DEPARTMENT": 5,
    "EMPLOYEE": 2863
  },
  "success": true
}
```

### 3. Properties Perspective: Schema Discovery

**SDK Call:**
```sdk
# Discover available properties across matching entities
properties = db.properties.find(QUERY)
___SPLIT___
// Discover available properties across matching entities
const properties = await db.properties.find(QUERY);
```

**Generated Cypher Queries:**
```cypher
-- Get entity-specific properties
MATCH (record:__RUSHDB__LABEL__RECORD__:`DEPARTMENT` { __RUSHDB__KEY__PROJECT__ID__: $projectId })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
WITH record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
UNWIND keys(record) as propertyName
RETURN collect(DISTINCT propertyName) as fields

-- Get global property metadata
MATCH (property:__RUSHDB__LABEL__PROPERTY__ { projectId: $id })
RETURN collect(DISTINCT property { .id, .metadata, .name, .type, .projectId }) as properties
```

**Resulting Data:**
```json
{
  "data": [
    {
      "id": "01974151-41f3-7ecc-a42c-2a6a336f856f",
      "name": "name",
      "type": "string",
      "metadata": ""
    },
    {
      "id": "01974151-41f4-7c7e-a9bd-a28cffae6594",
      "name": "description",
      "type": "string",
      "metadata": ""
    },
    {
      "id": "01974151-41f5-7635-81a1-budget",
      "name": "budget",
      "type": "number",
      "metadata": ""
    }
  ],
  "success": true
}
```

### 4. Values Perspective: Data Range Discovery

**SDK Call:**
```sdk
# Get distinct values and ranges for specific properties
values = db.properties.values(property_id, QUERY)
___SPLIT___
// Get distinct values and ranges for specific properties
const values = await db.properties.values(propertyId, QUERY);
```

**Generated Cypher Query:**
```cypher
MATCH (record:__RUSHDB__LABEL__RECORD__:`DEPARTMENT` { __RUSHDB__KEY__PROJECT__ID__: $projectId })
     <-[value:__RUSHDB__RELATION__VALUE__]-(property:__RUSHDB__LABEL__PROPERTY__ { id: $id })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
AND record[property.name] IS NOT NULL AND property.type <> 'vector'
WITH property, record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
WITH record[property.name] AS propValue, property.type AS propType
ORDER BY record.__RUSHDB__KEY__ID__
WITH apoc.coll.toSet(apoc.coll.flatten(collect(DISTINCT propValue))) AS values, propType as type
UNWIND values AS v
WITH values, type,
     min(CASE type WHEN 'datetime' THEN datetime(v) ELSE toFloatOrNull(v) END) AS minValue,
     max(CASE type WHEN 'datetime' THEN datetime(v) ELSE toFloatOrNull(v) END) AS maxValue
RETURN {
  values: values[0..1000],
  min: CASE type WHEN 'datetime' THEN toString(minValue) ELSE minValue END,
  max: CASE type WHEN 'datetime' THEN toString(maxValue) ELSE maxValue END,
  type: type
} AS result
```

**Resulting Data:**
```json
{
  "data": {
    "values": [
      "Research and Development",
      "Engineering Excellence Division",
      "Product Innovation Center",
      "Advanced Technology Department",
      "Strategic Development Unit"
    ],
    "min": null,
    "max": null,
    "type": "string"
  },
  "success": true
}
```

### 5. Relationships Perspective: Connection Discovery

**SDK Call:**
```sdk
# Discover relationships between matching entities
relationships = db.relationships.find(QUERY)
___SPLIT___
// Discover relationships between matching entities
const relationships = await db.relationships.find(QUERY);
```

**Generated Cypher Queries:**
```cypher
-- Get relationship details
MATCH (record:__RUSHDB__LABEL__RECORD__:`DEPARTMENT` { __RUSHDB__KEY__PROJECT__ID__: $projectId })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
WITH record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
MATCH (record)-[rel]-(neighbor:__RUSHDB__LABEL__RECORD__)
SKIP 0 LIMIT 1000
RETURN DISTINCT
CASE
  WHEN startNode(rel) = record THEN {
    sourceId: record.__RUSHDB__KEY__ID__,
    sourceLabel: [label IN labels(record) WHERE label <> "__RUSHDB__LABEL__RECORD__"][0],
    targetId: neighbor.__RUSHDB__KEY__ID__,
    targetLabel: [label IN labels(neighbor) WHERE label <> "__RUSHDB__LABEL__RECORD__"][0],
    type: type(rel)
  }
  ELSE {
    sourceId: neighbor.__RUSHDB__KEY__ID__,
    sourceLabel: [label IN labels(neighbor) WHERE label <> "__RUSHDB__LABEL__RECORD__"][0],
    targetId: record.__RUSHDB__KEY__ID__,
    targetLabel: [label IN labels(record) WHERE label <> "__RUSHDB__LABEL__RECORD__"][0],
    type: type(rel)
  }
END AS relation

-- Get relationship count
MATCH (record:__RUSHDB__LABEL__RECORD__:`DEPARTMENT` { __RUSHDB__KEY__PROJECT__ID__: $projectId })
WHERE (any(value IN record.name WHERE value =~ "(?i).*e.*"))
OPTIONAL MATCH (record)--(record1:PROJECT)
WHERE ((any(value IN record1.budget WHERE value <= 10000000) XOR
        any(value IN record1.budget WHERE value >= 15000000)))
OPTIONAL MATCH (record1)--(record2:EMPLOYEE)
WHERE (any(value IN record2.salary WHERE value >= 300000))
WITH record, record1, record2
WHERE record IS NOT NULL AND (record1 IS NOT NULL AND record2 IS NOT NULL)
MATCH (record)-[rel]-(target:__RUSHDB__LABEL__RECORD__)
RETURN count(DISTINCT rel) as total
```

**Resulting Data:**
```json
{
  "data": [
    {
      "targetLabel": "PROJECT",
      "targetId": "01974151-41f6-78b8-9d4b-ad5bd184baf9",
      "type": "RUSHDB_DEFAULT_RELATION",
      "sourceId": "01974151-41f4-7c7e-a9bd-a28df7703077",
      "sourceLabel": "DEPARTMENT"
    },
    {
      "targetLabel": "PROJECT",
      "targetId": "01974151-41f6-78b8-9d4b-ad5190bb4abf",
      "type": "RUSHDB_DEFAULT_RELATION",
      "sourceId": "01974151-41f4-7c7e-a9bd-a28df7703077",
      "sourceLabel": "DEPARTMENT"
    },
    {
      "targetLabel": "COMPANY",
      "targetId": "01974151-41f0-7309-946f-2a45a8391ed8",
      "type": "RUSHDB_DEFAULT_RELATION",
      "sourceId": "01974151-41f4-7c7e-a9bd-a28df7703077",
      "sourceLabel": "DEPARTMENT"
    }
  ],
  "total": 25,
  "success": true
}
```

### The Perforating Query Advantage

This unified approach delivers **complete data observability** from a single query interface:

```mermaid
graph TB
    subgraph "Single SDK Query"
        Q[QUERY Object]
    end

    subgraph "Perforating Architecture"
        P1[Query Parser]
        P2[Cypher Generator]
        P3[Execution Engine]
        P4[Result Aggregator]
    end

    subgraph "Five Perspectives"
        R1[Records<br/>Actual Data]
        R2[Labels<br/>Entity Types]
        R3[Properties<br/>Schema Info]
        R4[Values<br/>Data Ranges]
        R5[Relationships<br/>Connections]
    end

    Q --> P1
    P1 --> P2
    P2 --> P3
    P3 --> P4
    P4 --> R1
    P4 --> R2
    P4 --> R3
    P4 --> R4
    P4 --> R5
```

### Performance Characteristics

**Traditional Approach (5 separate API calls):**
- Records: 250ms
- Labels: 180ms
- Properties: 320ms
- Values: 420ms
- Relationships: 290ms
- **Total: 1,460ms**

**LMPG Perforating Approach (parallel execution):**
- All perspectives: **~300ms**
- **Performance gain: 80% reduction**

The key insight is that RushDB's property-centric architecture allows the same filtered record set to be analyzed from multiple perspectives without re-executing the expensive traversal logic. The WHERE clauses are shared across all perspective queries, enabling massive optimization through result set reuse.

### Real-World Applications of Graph Perforating

The unified query interface enables powerful real-world applications that would require complex joins and multiple API calls in traditional databases:

**E-commerce Intelligence:**
```sdk
# Single query for comprehensive product analysis
products = db.records.find({
    "labels": ["Product"],
    "where": {
        "price": { "$gte": 50, "$lte": 500 },
        "rating": { "$gte": 4.0 },
        "CATEGORY": {
            "trending": True,
            "REVIEW": {
                "sentiment": { "$gte": 0.7 }
            }
        }
    }
})

# Simultaneously provides:
# - Product records (actual inventory data)
# - Available categories (PRODUCT, CATEGORY, REVIEW entity types)
# - Price/rating distributions (min/max values across properties)
# - Cross-entity relationships (product-category-review connections)
___SPLIT___
// Single query for comprehensive product analysis
const products = await db.records.find({
  labels: ["Product"],
  where: {
    price: { $gte: 50, $lte: 500 },
    rating: { $gte: 4.0 },
    CATEGORY: {
      trending: true,
      REVIEW: {
        sentiment: { $gte: 0.7 }
      }
    }
  }
});

// Simultaneously provides:
// - Product records (actual inventory data)
// - Available categories (PRODUCT, CATEGORY, REVIEW entity types)
// - Price/rating distributions (min/max values across properties)
// - Cross-entity relationships (product-category-review connections)
```

**IoT Sensor Analysis:**
```sdk
# Multi-dimensional sensor data analysis
sensors = db.records.find({
    "labels": ["Sensor"],
    "where": {
        "temperature": { "$between": [20, 25] },
        "humidity": { "$lte": 60 },
        "LOCATION": {
            "region": "west-coast",
            "BUILDING": {
                "efficiency_rating": { "$gte": 4.0 }
            }
        }
    }
})

# Automatic discovery of:
# - Sensor readings (filtered data points)
# - Equipment types (SENSOR, LOCATION, BUILDING labels)
# - Environmental ranges (temperature/humidity distributions)
# - Spatial relationships (sensor-location-building hierarchy)
___SPLIT___
// Multi-dimensional sensor data analysis
const sensors = await db.records.find({
  labels: ["Sensor"],
  where: {
    temperature: { $between: [20, 25] },
    humidity: { $lte: 60 },
    LOCATION: {
      region: "west-coast",
      BUILDING: {
        efficiency_rating: { $gte: 4.0 }
      }
    }
  }
});

// Automatic discovery of:
// - Sensor readings (filtered data points)
// - Equipment types (SENSOR, LOCATION, BUILDING labels)
// - Environmental ranges (temperature/humidity distributions)
// - Spatial relationships (sensor-location-building hierarchy)
```

**Financial Portfolio Analysis:**
```sdk
# Complex risk assessment across investment hierarchy
investments = db.records.find({
    "labels": ["Investment"],
    "where": {
        "value": { "$gte": 1000000 },
        "PORTFOLIO": {
            "risk_score": { "$lte": 7 },
            "INVESTOR": {
                "net_worth": { "$gte": 10000000 }
            }
        }
    }
})

# Comprehensive risk profiling reveals:
# - Investment instruments (matching financial products)
# - Entity classification (INVESTMENT, PORTFOLIO, INVESTOR types)
# - Value distributions (investment amounts, risk scores, net worth ranges)
# - Ownership networks (investor-portfolio-investment relationships)
___SPLIT___
// Complex risk assessment across investment hierarchy
const investments = await db.records.find({
  labels: ["Investment"],
  where: {
    value: { $gte: 1000000 },
    PORTFOLIO: {
      risk_score: { $lte: 7 },
      INVESTOR: {
        net_worth: { $gte: 10000000 }
      }
    }
  }
});

// Comprehensive risk profiling reveals:
// - Investment instruments (matching financial products)
// - Entity classification (INVESTMENT, PORTFOLIO, INVESTOR types)
// - Value distributions (investment amounts, risk scores, net worth ranges)
// - Ownership networks (investor-portfolio-investment relationships)
```

---

*Explore [Search Capabilities](https://docs.rushdb.com/concepts/search/introduction)*

## The Unified Query Revolution

The most transformative aspect of LMPG is its **unified query interface** that eliminates the complexity of traditional database interactions:

```mermaid
graph LR
    subgraph "Before: Multiple Interfaces"
        B1[Records API]
        B2[Schema API]
        B3[Metadata API]
        B4[Analytics API]
        B5[Relationship API]
    end

    subgraph "After: Single DTO"
        A1[Universal Query Interface]
    end

    subgraph "All Perspectives"
        P1[Records]
        P2[Labels]
        P3[Properties]
        P4[Values]
        P5[Relationships]
    end

    B1 --> P1
    B2 --> P2
    B3 --> P3
    B4 --> P4
    B5 --> P5

    A1 --> P1
    A1 --> P2
    A1 --> P3
    A1 --> P4
    A1 --> P5
```

**Key Benefits of the Unified Interface:**

- **Single DTO, infinite perspectives**: One query interface for all data aspects
- **Properties as dynamic indices**: Self-optimizing performance without manual tuning
- **Database self-awareness**: Automatic adaptation to data patterns and usage
- **Perforating query architecture**: Skip expensive operations for consistent performance
- **Cross-domain insights**: Discover relationships across unrelated data domains

This revolutionary approach means developers no longer need to learn separate APIs for different database operations. Whether you need records, schema information, property metadata, value ranges, or relationship mappings - it all comes from the same intuitive JSON query structure demonstrated in the Graph Perforating section above.

### Revolutionary Applications Enabled by Unified Interface

The unified query interface opens up entirely new possibilities across multiple domains, enabling sophisticated applications without writing complex database code:

#### 1. Cataloging Indeterminate Data

**Challenge**: Scientific datasets, IoT streams, and user-generated content often have unpredictable schemas and evolving structures.

**LMPG Solution**: Automatic schema adaptation with unified querying across all data perspectives.

```sdk
# Automatically catalog any scientific data structure
research_data = db.records.create({
    "label": "Experiment",
    "data": {
        "experiment_id": "EXP-2024-001",
        "temperature": 23.5,
        "unexpected_compound": "C8H10N4O2",  # New discovery
        "readings": [1.2, 3.4, 5.6],
        "metadata": {
            "researcher": "Dr. Smith",
            "equipment": "Spectrometer-X200"
        }
    }
})

# Later, discover all experiments with any temperature data
temperature_studies = db.records.find({
    "where": {
        "temperature": { "$exists": True }
    }
})

# Automatically discover new property types
new_properties = db.properties.find()  # Finds "unexpected_compound" property
property_values = db.properties.values(compound_property_id)  # Get all compound values
___SPLIT___
// Automatically catalog any scientific data structure
const researchData = await db.records.create({
  label: "Experiment",
  data: {
    experiment_id: "EXP-2024-001",
    temperature: 23.5,
    unexpected_compound: "C8H10N4O2",  // New discovery
    readings: [1.2, 3.4, 5.6],
    metadata: {
      researcher: "Dr. Smith",
      equipment: "Spectrometer-X200"
    }
  }
});

// Later, discover all experiments with any temperature data
const temperatureStudies = await db.records.find({
  where: {
    temperature: { $exists: true }
  }
});

// Automatically discover new property types
const newProperties = await db.properties.find();  // Finds "unexpected_compound" property
const propertyValues = await db.properties.values(compoundPropertyId);  // Get all compound values
```

**Result**: Zero-configuration data cataloging that automatically adapts to new discoveries.

#### 2. AI-Driven Scientific Research Loops

**Challenge**: Modern AI research requires iterative data exploration, hypothesis generation, and validation across evolving datasets.

**LMPG Solution**: Unified interface enables AI agents to autonomously explore data relationships and generate research hypotheses.

```sdk
# AI research agent workflow
class ResearchAgent:
    def explore_correlations(self):
        # Discover all numeric properties
        numeric_props = db.properties.find({"where": {"type": "number"}})

        for prop in numeric_props["data"]:
            # Get value distributions
            distribution = db.properties.values(prop["id"])

            # Find correlating entities
            correlated_records = db.records.find({
                "where": {prop["name"]: {"$gte": distribution["data"]["min"]}}
            })

            # Discover relationship patterns
            relationships = db.relationships.find(correlated_records["query"])

            # Generate hypothesis based on discovered patterns
            yield self.generate_hypothesis(prop, distribution, relationships)

    def validate_hypothesis(self, hypothesis):
        # Use unified interface to test hypothesis across all data perspectives
        validation_query = {
            "where": hypothesis["conditions"]
        }

        results = {
            "records": db.records.find(validation_query),
            "patterns": db.relationships.find(validation_query),
            "distributions": [db.properties.values(p) for p in hypothesis["properties"]]
        }

        return self.analyze_validation(results)
___SPLIT___
// AI research agent workflow
class ResearchAgent {
  async exploreCorrelations() {
    // Discover all numeric properties
    const numericProps = await db.properties.find({where: {type: "number"}});

    for (const prop of numericProps.data) {
      // Get value distributions
      const distribution = await db.properties.values(prop.id);

      // Find correlating entities
      const correlatedRecords = await db.records.find({
        where: {[prop.name]: {$gte: distribution.data.min}}
      });

      // Discover relationship patterns
      const relationships = await db.relationships.find(correlatedRecords.query);

      // Generate hypothesis based on discovered patterns
      yield this.generateHypothesis(prop, distribution, relationships);
    }
  }

  async validateHypothesis(hypothesis) {
    // Use unified interface to test hypothesis across all data perspectives
    const validationQuery = {
      where: hypothesis.conditions
    };

    const results = {
      records: await db.records.find(validationQuery),
      patterns: await db.relationships.find(validationQuery),
      distributions: await Promise.all(
        hypothesis.properties.map(p => db.properties.values(p))
      )
    };

    return this.analyzeValidation(results);
  }
}
```

**Result**: AI agents can autonomously discover patterns, generate hypotheses, and validate theories through iterative data exploration.

#### 3. Unbeatable E-commerce Filtering (Zero Code)

**Challenge**: Building sophisticated product filtering requires complex database queries and extensive frontend logic.

**LMPG Solution**: Unified interface automatically generates filters from data, requires zero manual configuration.

```sdk
# Auto-generate complete filtering interface
class AutoFilter:
    def __init__(self, category="Product"):
        self.category = category

    def get_filter_options(self):
        # Single query gets all filter possibilities
        base_query = {"labels": [self.category]}

        return {
            # Available products
            "products": db.records.find(base_query),

            # Auto-discovered filter categories
            "categories": db.labels.find(base_query),

            # All filterable properties
            "properties": db.properties.find(base_query),

            # Value ranges for each property
            "ranges": {
                prop["name"]: db.properties.values(prop["id"], base_query)
                for prop in db.properties.find(base_query)["data"]
            }
        }

    def apply_filters(self, user_filters):
        # User filters automatically become query conditions
        filtered_query = {
            "labels": [self.category],
            "where": user_filters  # Direct mapping from UI
        }

        return {
            "products": db.records.find(filtered_query),
            "updated_ranges": self.get_updated_ranges(filtered_query),
            "related_categories": db.labels.find(filtered_query)
        }

# Frontend automatically adapts to any product catalog
auto_filter = AutoFilter("Product")
filter_ui = auto_filter.get_filter_options()

# User applies filters - no backend code needed
user_selection = {
    "price": {"$gte": 100, "$lte": 500},
    "rating": {"$gte": 4.0},
    "brand": {"$in": ["Nike", "Adidas"]},
    "CATEGORY": {
        "trending": True
    }
}

filtered_results = auto_filter.apply_filters(user_selection)
___SPLIT___
// Auto-generate complete filtering interface
class AutoFilter {
  constructor(category = "Product") {
    this.category = category;
  }

  async getFilterOptions() {
    // Single query gets all filter possibilities
    const baseQuery = {labels: [this.category]};

    const properties = await db.properties.find(baseQuery);

    return {
      // Available products
      products: await db.records.find(baseQuery),

      // Auto-discovered filter categories
      categories: await db.labels.find(baseQuery),

      // All filterable properties
      properties: properties,

      // Value ranges for each property
      ranges: await Promise.all(
        properties.data.map(async prop => ({
          [prop.name]: await db.properties.values(prop.id, baseQuery)
        }))
      )
    };
  }

  async applyFilters(userFilters) {
    // User filters automatically become query conditions
    const filteredQuery = {
      labels: [this.category],
      where: userFilters  // Direct mapping from UI
    };

    return {
      products: await db.records.find(filteredQuery),
      updatedRanges: await this.getUpdatedRanges(filteredQuery),
      relatedCategories: await db.labels.find(filteredQuery)
    };
  }
}

// Frontend automatically adapts to any product catalog
const autoFilter = new AutoFilter("Product");
const filterUI = await autoFilter.getFilterOptions();

// User applies filters - no backend code needed
const userSelection = {
  price: {$gte: 100, $lte: 500},
  rating: {$gte: 4.0},
  brand: {$in: ["Nike", "Adidas"]},
  CATEGORY: {
    trending: true
  }
};

const filteredResults = await autoFilter.applyFilters(userSelection);
```

**Result**: Complete e-commerce filtering interface that automatically adapts to any product catalog without writing filtering logic.

#### 4. Real-Time Analytical Workloads

**Challenge**: Traditional analytical queries require complex aggregations, joins, and pre-computed views.

**LMPG Solution**: Unified interface enables real-time analytics across any data dimension without pre-configuration.

```sdk
# Real-time business intelligence dashboard
class RealTimeAnalytics:
    def __init__(self):
        self.metrics = {}

    def get_sales_insights(self, time_range):
        base_query = {
            "labels": ["Sale"],
            "where": {
                "timestamp": {
                    "$gte": time_range["start"],
                    "$lte": time_range["end"]
                }
            }
        }

        # Single unified call gets all analytics
        return {
            # Core sales data
            "sales": db.records.find(base_query),

            # Auto-discovered segments
            "segments": db.labels.find(base_query),

            # All sales dimensions
            "dimensions": db.properties.find(base_query),

            # Value distributions per dimension
            "distributions": {
                "revenue": db.properties.values("revenue", base_query),
                "products": db.properties.values("product_id", base_query),
                "regions": db.properties.values("region", base_query),
                "channels": db.properties.values("channel", base_query)
            },

            # Relationship insights
            "correlations": db.relationships.find(base_query)
        }

    def drill_down(self, dimension, value):
        # Dynamic drill-down without predefined hierarchies
        drill_query = {
            "where": {
                dimension: value,
                "timestamp": {"$gte": "2024-01-01"}
            }
        }

        return {
            "details": db.records.find(drill_query),
            "related_dimensions": db.properties.find(drill_query),
            "cross_correlations": db.relationships.find(drill_query)
        }

# Usage: Real-time dashboard that adapts to any business
analytics = RealTimeAnalytics()

# Get comprehensive sales insights
insights = analytics.get_sales_insights({
    "start": "2024-01-01",
    "end": "2024-12-31"
})

# Dynamic drill-down based on user clicks
region_details = analytics.drill_down("region", "North America")
product_details = analytics.drill_down("product_category", "Electronics")
___SPLIT___
// Real-time business intelligence dashboard
class RealTimeAnalytics {
  constructor() {
    this.metrics = {};
  }

  async getSalesInsights(timeRange) {
    const baseQuery = {
      labels: ["Sale"],
      where: {
        timestamp: {
          $gte: timeRange.start,
          $lte: timeRange.end
        }
      }
    };

    // Single unified call gets all analytics
    return {
      // Core sales data
      sales: await db.records.find(baseQuery),

      // Auto-discovered segments
      segments: await db.labels.find(baseQuery),

      // All sales dimensions
      dimensions: await db.properties.find(baseQuery),

      // Value distributions per dimension
      distributions: {
        revenue: await db.properties.values("revenue", baseQuery),
        products: await db.properties.values("product_id", baseQuery),
        regions: await db.properties.values("region", baseQuery),
        channels: await db.properties.values("channel", baseQuery)
      },

      // Relationship insights
      correlations: await db.relationships.find(baseQuery)
    };
  }

  async drillDown(dimension, value) {
    // Dynamic drill-down without predefined hierarchies
    const drillQuery = {
      where: {
        [dimension]: value,
        timestamp: {$gte: "2024-01-01"}
      }
    };

    return {
      details: await db.records.find(drillQuery),
      relatedDimensions: await db.properties.find(drillQuery),
      crossCorrelations: await db.relationships.find(drillQuery)
    };
  }
}

// Usage: Real-time dashboard that adapts to any business
const analytics = new RealTimeAnalytics();

// Get comprehensive sales insights
const insights = await analytics.getSalesInsights({
  start: "2024-01-01",
  end: "2024-12-31"
});

// Dynamic drill-down based on user clicks
const regionDetails = await analytics.drillDown("region", "North America");
const productDetails = await analytics.drillDown("product_category", "Electronics");
```

**Result**: Real-time analytics dashboards that automatically discover and visualize any business dimension without pre-configuration.

#### 5. Healthcare Data Integration

**Challenge**: Medical data comes from disparate systems with different schemas and requires complex integration.

**LMPG Solution**: Automatic schema harmonization enables unified patient views across all medical systems.

```sdk
# Unified patient data across all medical systems
class MedicalDataIntegration:
    def integrate_patient_data(self, patient_id):
        # Query across all medical record types
        base_query = {
            "where": {
                "patient_id": patient_id
            }
        }

        return {
            # All medical records
            "records": db.records.find(base_query),

            # Auto-discovered record types
            "record_types": db.labels.find(base_query),

            # All medical properties
            "medical_fields": db.properties.find(base_query),

            # Value ranges for medical metrics
            "vital_ranges": {
                field["name"]: db.properties.values(field["id"], base_query)
                for field in db.properties.find(base_query)["data"]
                if field["name"] in ["blood_pressure", "heart_rate", "temperature"]
            },

            # Medical relationships
            "care_relationships": db.relationships.find(base_query)
        }

    def find_similar_cases(self, symptoms, demographics):
        # Cross-system case similarity without predefined schemas
        similarity_query = {
            "where": {
                **symptoms,  # Any symptom properties
                **demographics,  # Any demographic properties
            }
        }

        return {
            "similar_patients": db.records.find(similarity_query),
            "common_patterns": db.relationships.find(similarity_query),
            "outcome_distributions": db.properties.values("outcome", similarity_query)
        }

# Usage: Instant integration across any medical system
medical = MedicalDataIntegration()

# Complete patient view from all systems
patient_data = medical.integrate_patient_data("PAT-12345")

# Find similar cases for treatment planning
similar_cases = medical.find_similar_cases(
    symptoms={"chest_pain": True, "shortness_of_breath": True},
    demographics={"age": {"$between": [45, 65]}, "gender": "male"}
)
___SPLIT___
// Unified patient data across all medical systems
class MedicalDataIntegration {
  async integratePatientData(patientId) {
    // Query across all medical record types
    const baseQuery = {
      where: {
        patient_id: patientId
      }
    };

    const properties = await db.properties.find(baseQuery);
    const vitalFields = properties.data.filter(field =>
      ["blood_pressure", "heart_rate", "temperature"].includes(field.name)
    );

    return {
      // All medical records
      records: await db.records.find(baseQuery),

      // Auto-discovered record types
      recordTypes: await db.labels.find(baseQuery),

      // All medical properties
      medicalFields: properties,

      // Value ranges for medical metrics
      vitalRanges: await Promise.all(
        vitalFields.map(async field => ({
          [field.name]: await db.properties.values(field.id, baseQuery)
        }))
      ),

      // Medical relationships
      careRelationships: await db.relationships.find(baseQuery)
    };
  }

  async findSimilarCases(symptoms, demographics) {
    // Cross-system case similarity without predefined schemas
    const similarityQuery = {
      where: {
        ...symptoms,  // Any symptom properties
        ...demographics,  // Any demographic properties
      }
    };

    return {
      similarPatients: await db.records.find(similarityQuery),
      commonPatterns: await db.relationships.find(similarityQuery),
      outcomeDistributions: await db.properties.values("outcome", similarityQuery)
    };
  }
}

// Usage: Instant integration across any medical system
const medical = new MedicalDataIntegration();

// Complete patient view from all systems
const patientData = await medical.integratePatientData("PAT-12345");

// Find similar cases for treatment planning
const similarCases = await medical.findSimilarCases(
  {chest_pain: true, shortness_of_breath: true},
  {age: {$between: [45, 65]}, gender: "male"}
);
```

**Result**: Unified patient views and intelligent case matching across any medical system without manual integration work.

These examples demonstrate how LMPG's unified query interface eliminates the complexity barrier that typically prevents sophisticated data applications. Developers can now build AI-driven research tools, zero-code filtering interfaces, real-time analytics, and cross-system integrations using the same simple JSON query structure, enabling unprecedented innovation across all domains.

## Migration and Integration Strategies

### From Relational Databases

**Before (SQL):**
```sql
SELECT p.name, p.price, c.name as category
FROM products p
JOIN categories c ON p.category_id = c.id
JOIN product_attributes pa ON p.id = pa.product_id
JOIN attributes a ON pa.attribute_id = a.id
WHERE p.price > 100
  AND a.name = 'color'
  AND pa.value = 'red';
```

**After (LMPG):**
```javascript
const results = await rushdb.records.find({
  labels: ['Product'],
  where: {
    price: { $gt: 100 },
    color: 'red'
  }
});
```

### From Document Databases

**Before (MongoDB):**
```javascript
db.products.aggregate([
  { $match: { price: { $gt: 100 } } },
  { $lookup: {
      from: "categories",
      localField: "categoryId",
      foreignField: "_id",
      as: "category"
  }},
  { $unwind: "$category" },
  { $match: { "attributes.color": "red" } }
]);
```

**After (LMPG):**
```javascript
// Same query as above - LMPG handles relationships automatically
const results = await rushdb.records.find({
  where: {
    price: { $gt: 100 },
    color: 'red'
  }
});
```

## Future of LMPG Architecture

The Labeled Meta Property Graph represents a fundamental shift toward **property-centric data modeling**. As data becomes increasingly interconnected and diverse, LMPG's ability to:

1. **Automatically discover relationships** through shared properties
2. **Adapt to evolving schemas** without migration overhead
3. **Enable cross-domain insights** through property traversal
4. **Simplify complex queries** with intuitive JSON syntax
5. **Integrate vector operations** for AI-powered applications
6. **Provide unified query interface** across all data perspectives
7. **Self-optimize through property-based indexing** for massive scale

...makes it the ideal architecture for the next generation of data-intensive applications.

### The Self-Aware Database Revolution

LMPG introduces the concept of **database self-awareness** where:

```mermaid
graph TB
    subgraph "Traditional Database"
        T1[Static Schema] --> T2[Manual Optimization]
        T2 --> T3[Query Planning]
        T3 --> T4[Execution]
    end

    subgraph "Self-Aware LMPG Database"
        S1[Dynamic Property Discovery] --> S2[Automatic Index Creation]
        S2 --> S3[Pattern Recognition]
        S3 --> S4[Query Optimization]
        S4 --> S5[Performance Adaptation]
        S5 --> S1
    end

    T4 --> TR[Static Performance]
    S5 --> SR[Adaptive Performance]
```

**Key Self-Awareness Features:**
- **Automatic schema evolution** without downtime
- **Dynamic query optimization** based on data patterns
- **Property relationship inference** through usage analysis
- **Performance self-tuning** based on access patterns
- **Cross-domain insight generation** through property overlap discovery

### Emerging Applications

**1. AI-Native Data Architecture:**
- Vector embeddings as first-class properties
- Semantic search integrated with structured queries
- LLM-generated property relationships
- Automated data pipeline optimization

**2. Real-Time Analytics at Scale:**
- Stream processing with property-based filtering
- Event correlation through shared properties
- Dynamic aggregation without pre-computation
- Sub-second response times on billion-record datasets

**3. Knowledge Graph Evolution:**
- Automatic ontology generation from data patterns
- Cross-domain knowledge discovery
- Semantic relationship inference
- Dynamic concept emergence

### Industry Transformation Potential

LMPG is positioned to transform how organizations handle data complexity:

- **Financial Services**: Real-time risk assessment across interconnected portfolios
- **Healthcare**: Patient data integration across disparate systems
- **Manufacturing**: IoT sensor correlation for predictive maintenance
- **Retail**: Customer behavior analysis across all touchpoints
- **Research**: Scientific data integration and hypothesis generation

## Getting Started with LMPG

### Quick Setup

```bash
# Install RushDB SDK
npm install @rushdb/javascript-sdk

# Or use Python
pip install rushdb
```

### First LMPG Implementation

```sdk
# Push any JSON - LMPG structure is created automatically
from rushdb import RushDB

db = RushDB('your-api-key')

customer_data = db.records.create_many({
    "label": "Customer",
    "data": [
        {
            "name": "Alice Johnson",
            "email": "alice@example.com",
            "preferences": {
                "color": "blue",
                "priceRange": "premium"
            },
            "orders": [
                {"product": "Laptop", "amount": 1299},
                {"product": "Mouse", "amount": 79}
            ]
        }
    ]
})

# Query across all automatically-created relationships
premium_customers = db.records.find({
    "labels": ["Customer"],
    "where": {
        "preferences": {
            "priceRange": "premium",
        },
        "orders": {
            "amount": {"$gt": 1000}
        }
    }
})
___SPLIT___
// Push any JSON - LMPG structure is created automatically
import RushDB from '@rushdb/javascript-sdk';

const db = new RushDB('your-api-key');

const customerData = await db.records.createMany({
  label: "Customer",
  data: [
    {
      name: "Alice Johnson",
      email: "alice@example.com",
      preferences: {
        color: "blue",
        priceRange: "premium"
      },
      orders: [
        { product: "Laptop", amount: 1299 },
        { product: "Mouse", amount: 79 }
      ]
    }
  ]
});

// Query across all automatically-created relationships
const premiumCustomers = await db.records.find({
  labels: ["Customer"],
  where: {
    preferences: {
      priceRange: "premium",
    },
    orders: {
      amount: { $gt: 1000 }
    }
  }
});
```

## Conclusion

RushDB's Labeled Meta Property Graph architecture represents a paradigm shift in database design. By making properties first-class citizens, LMPG enables:

- **Zero-configuration data modeling** with automatic schema inference
- **Automatic relationship discovery** through property overlap analysis
- **Cross-domain query capabilities** with unified interface
- **Simplified development workflows** using intuitive JSON syntax
- **AI-ready data structures** with native vector support
- **Database self-awareness** through dynamic property indexing
- **Perforating query performance** that skips expensive operations
- **Multi-perspective data access** from single query interface

### The Database of Tomorrow

The future of databases is not about forcing data into predefined structures, but about letting the data define its own relationships while providing intelligent optimization. LMPG makes this vision a reality, enabling developers to focus on building features rather than fighting with database schemas.

As applications become increasingly complex and data sources multiply, LMPG's property-centric approach will become the standard for managing interconnected data at scale. The question isn't whether to adopt this architecture – it's how quickly you can start leveraging its power for your applications.

**Key Takeaways:**
- **Single DTO, infinite perspectives**: One query interface for all data aspects
- **Properties as dynamic indices**: Self-optimizing performance without manual tuning
- **Database self-awareness**: Automatic adaptation to data patterns and usage
- **Perforating query architecture**: Skip expensive operations for consistent performance
- **Cross-domain insights**: Discover relationships across unrelated data domains
