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

# Field Mappings

> Map source CSV or JSON fields onto the gu1 entity model with type conversions, default values, and transformations applied during data ingestion.

## Overview

Field Mappings define how your custom schema fields translate to gu1's unified entity model. Each mapping can include transformations to format, calculate, or conditionally process data during import.

<Info>
  Mappings bridge the gap between your data structure and gu1's entity model, enabling seamless data ingestion from any source.
</Info>

## Create Field Mapping

Create a mapping configuration for your custom schema.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/custom-schemas/mappings \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "KYB Company Mapping",
      "description": "Maps company data to gu1 entity model",
      "sourceSchemaId": "550e8400-e29b-41d4-a716-446655440000",
      "targetSchemaType": "gueno_entity",
      "mappingData": {
        "mappings": [
          {
            "id": "1",
            "sourceField": "company_name",
            "targetField": "name",
            "transformation": {
              "type": "direct"
            },
            "required": true,
            "dataType": "string"
          },
          {
            "id": "2",
            "sourceField": "tax_id",
            "targetField": "external_id",
            "transformation": {
              "type": "format",
              "expression": "value.trim().toUpperCase()"
            },
            "required": true,
            "dataType": "string"
          },
          {
            "id": "3",
            "sourceField": "annual_revenue",
            "targetField": "entityData.revenue",
            "transformation": {
              "type": "calculate",
              "expression": "value * 1000"
            },
            "required": false,
            "dataType": "number"
          }
        ],
        "validation": {
          "strictMode": true,
          "allowExtraFields": false,
          "requiredFields": ["name", "external_id"]
        }
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://api.gu1.ai/custom-schemas/mappings', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: 'KYB Company Mapping',
      description: 'Maps company data to gu1 entity model',
      sourceSchemaId: '550e8400-e29b-41d4-a716-446655440000',
      targetSchemaType: 'gueno_entity',
      mappingData: {
        mappings: [
          {
            id: '1',
            sourceField: 'company_name',
            targetField: 'name',
            transformation: { type: 'direct' },
            required: true,
            dataType: 'string'
          }
        ],
        validation: {
          strictMode: true,
          allowExtraFields: false,
          requiredFields: ['name', 'external_id']
        }
      }
    })
  });
  ```
</CodeGroup>

### Request Body

| Field              | Type   | Required | Description                                |
| ------------------ | ------ | -------- | ------------------------------------------ |
| `name`             | string | Yes      | Mapping configuration name                 |
| `description`      | string | No       | Mapping description                        |
| `sourceSchemaId`   | uuid   | No       | Source custom schema ID                    |
| `targetSchemaType` | string | No       | Target schema type (e.g., "gueno\_entity") |
| `sourceSchemaName` | string | No       | Alternative to sourceSchemaId              |
| `targetSchemaName` | string | No       | Alternative to targetSchemaType            |
| `mappingData`      | object | Yes      | Mapping configuration                      |
| `industry`         | string | No       | Industry context                           |
| `collaborators`    | array  | No       | User IDs with access                       |

### Mapping Data Object

| Field                    | Type   | Required | Description             |
| ------------------------ | ------ | -------- | ----------------------- |
| `mappings`               | array  | Yes      | Array of field mappings |
| `templates`              | array  | No       | Template IDs to apply   |
| `validation`             | object | No       | Validation rules        |
| `transformationSettings` | object | No       | Processing settings     |

### Field Mapping Object

| Field            | Type    | Required | Description                               |
| ---------------- | ------- | -------- | ----------------------------------------- |
| `id`             | string  | Yes      | Unique mapping identifier                 |
| `sourceField`    | string  | Yes      | Source field name                         |
| `targetField`    | string  | Yes      | Target field name (supports dot notation) |
| `transformation` | object  | No       | Transformation to apply                   |
| `required`       | boolean | Yes      | Is field required                         |
| `dataType`       | string  | Yes      | Expected data type                        |
| `defaultValue`   | any     | No       | Default if source is null/missing         |
| `validationRule` | string  | No       | Custom validation expression              |

### Response

```json theme={null}
{
  "success": true,
  "mapping": {
    "id": "map_abc123",
    "name": "KYB Company Mapping",
    "description": "Maps company data to gu1 entity model",
    "sourceSchemaId": "550e8400-e29b-41d4-a716-446655440000",
    "targetSchemaType": "gueno_entity",
    "organizationId": "org_xyz",
    "createdBy": "user_123",
    "createdAt": "2025-10-03T12:00:00Z",
    "updatedAt": "2025-10-03T12:00:00Z",
    "mappingData": {
      "mappings": [...],
      "validation": {...}
    }
  }
}
```

## Transformation Types

### Direct Mapping

Copy value as-is with no changes:

```json theme={null}
{
  "transformation": {
    "type": "direct"
  }
}
```

### Format Transformation

Apply string, date, or number formatting:

```json theme={null}
{
  "transformation": {
    "type": "format",
    "expression": "value.trim().toUpperCase()",
    "parameters": {
      "dateFormat": "ISO8601",
      "decimalPlaces": 2
    }
  }
}
```

**Common Format Examples:**

```javascript theme={null}
// Trim and uppercase
"value.trim().toUpperCase()"

// Format date
"new Date(value).toISOString()"

// Format currency
"parseFloat(value).toFixed(2)"

// Clean phone number
"value.replace(/[^0-9]/g, '')"
```

### Calculate Transformation

Perform mathematical calculations:

```json theme={null}
{
  "transformation": {
    "type": "calculate",
    "expression": "value * 1000",
    "parameters": {
      "operator": "multiply",
      "operand": 1000
    }
  }
}
```

**Common Calculate Examples:**

```javascript theme={null}
// Convert thousands to actual value
"value * 1000"

// Calculate percentage
"(value / total) * 100"

// Sum multiple fields
"sourceData.field1 + sourceData.field2"

// Average calculation
"(field1 + field2 + field3) / 3"
```

### Conditional Transformation

Apply if/then logic:

```json theme={null}
{
  "transformation": {
    "type": "conditional",
    "expression": "value > 1000000 ? 'high' : value > 100000 ? 'medium' : 'low'",
    "parameters": {
      "conditions": [
        {"if": "value > 1000000", "then": "high"},
        {"if": "value > 100000", "then": "medium"},
        {"else": "low"}
      ]
    }
  }
}
```

### Lookup Transformation

Look up values from reference tables:

```json theme={null}
{
  "transformation": {
    "type": "lookup",
    "expression": "lookupTable[value] || 'unknown'",
    "parameters": {
      "lookupTable": {
        "US": "United States",
        "UK": "United Kingdom",
        "CA": "Canada"
      },
      "defaultValue": "unknown"
    }
  }
}
```

### Custom Transformation

Execute custom JavaScript:

```json theme={null}
{
  "transformation": {
    "type": "custom",
    "expression": "const parts = value.split('-'); return parts[0].toUpperCase();",
    "parameters": {
      "allowedFunctions": ["split", "toUpperCase", "trim"]
    }
  }
}
```

<Warning>
  Custom transformations have security restrictions. Only whitelisted JavaScript functions are allowed.
</Warning>

## Validation Rules

Configure validation behavior:

```json theme={null}
{
  "validation": {
    "strictMode": true,
    "allowExtraFields": false,
    "requiredFields": ["name", "external_id", "country"]
  }
}
```

| Setting            | Type    | Description                  |
| ------------------ | ------- | ---------------------------- |
| `strictMode`       | boolean | Fail on any validation error |
| `allowExtraFields` | boolean | Allow unmapped source fields |
| `requiredFields`   | array   | Fields that must have values |

## Transformation Settings

Configure processing behavior:

```json theme={null}
{
  "transformationSettings": {
    "errorHandling": "default",
    "batchSize": 100,
    "timeout": 30000
  }
}
```

| Setting         | Type   | Description                  |
| --------------- | ------ | ---------------------------- |
| `errorHandling` | enum   | `skip`, `fail`, or `default` |
| `batchSize`     | number | Records per batch (1-1000)   |
| `timeout`       | number | Timeout in milliseconds      |

## List Mappings

Get all mapping configurations for your organization:

```bash theme={null}
GET /custom-schemas/mappings
```

### Response

```json theme={null}
{
  "success": true,
  "mappings": [
    {
      "id": "map_abc123",
      "name": "KYB Company Mapping",
      "sourceSchemaId": "550e8400-e29b-41d4-a716-446655440000",
      "targetSchemaType": "gueno_entity",
      "createdAt": "2025-10-03T12:00:00Z"
    }
  ]
}
```

## Get Mapping

Retrieve a specific mapping configuration:

```bash theme={null}
GET /custom-schemas/mappings/:id
```

### Response

```json theme={null}
{
  "success": true,
  "mapping": {
    "id": "map_abc123",
    "name": "KYB Company Mapping",
    "description": "Maps company data to gu1 entity model",
    "mappingData": {
      "mappings": [...],
      "validation": {...}
    }
  }
}
```

## Update Mapping

Update an existing mapping configuration:

```bash theme={null}
PATCH /custom-schemas/mappings/:id
```

### Request Body

```json theme={null}
{
  "description": "Updated description",
  "mappingData": {
    "mappings": [
      {
        "id": "4",
        "sourceField": "new_field",
        "targetField": "entityData.newField",
        "transformation": { "type": "direct" },
        "required": false,
        "dataType": "string"
      }
    ]
  }
}
```

## Delete Mapping

Delete a mapping configuration:

```bash theme={null}
DELETE /custom-schemas/mappings/:id
```

## Complete Example: Banking Customer Mapping

```json theme={null}
{
  "name": "Banking Customer to Entity Mapping",
  "description": "Complete mapping for retail banking customers",
  "sourceSchemaId": "schema_banking_001",
  "targetSchemaType": "gueno_entity",
  "mappingData": {
    "mappings": [
      {
        "id": "1",
        "sourceField": "customer_id",
        "targetField": "external_id",
        "transformation": {
          "type": "format",
          "expression": "value.trim().toUpperCase()"
        },
        "required": true,
        "dataType": "string"
      },
      {
        "id": "2",
        "sourceField": "full_name",
        "targetField": "name",
        "transformation": { "type": "direct" },
        "required": true,
        "dataType": "string"
      },
      {
        "id": "3",
        "sourceField": "email",
        "targetField": "entityData.contact.email",
        "transformation": {
          "type": "format",
          "expression": "value.toLowerCase().trim()"
        },
        "required": true,
        "dataType": "string",
        "validationRule": "/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)"
      },
      {
        "id": "4",
        "sourceField": "account_balance",
        "targetField": "entityData.financial.balance",
        "transformation": {
          "type": "calculate",
          "expression": "Math.round(value * 100) / 100"
        },
        "required": false,
        "dataType": "number",
        "defaultValue": 0
      },
      {
        "id": "5",
        "sourceField": "account_balance",
        "targetField": "entityData.financial.balanceTier",
        "transformation": {
          "type": "conditional",
          "expression": "value > 100000 ? 'premium' : value > 10000 ? 'standard' : 'basic'"
        },
        "required": false,
        "dataType": "string"
      },
      {
        "id": "6",
        "sourceField": "country_code",
        "targetField": "country",
        "transformation": {
          "type": "lookup",
          "parameters": {
            "lookupTable": {
              "US": "United States",
              "UK": "United Kingdom",
              "CA": "Canada",
              "MX": "Mexico"
            },
            "defaultValue": "Unknown"
          }
        },
        "required": true,
        "dataType": "string"
      },
      {
        "id": "7",
        "sourceField": "risk_score",
        "targetField": "riskScore",
        "transformation": {
          "type": "calculate",
          "expression": "Math.min(Math.max(value, 0), 100)"
        },
        "required": false,
        "dataType": "number",
        "defaultValue": 0
      }
    ],
    "validation": {
      "strictMode": true,
      "allowExtraFields": false,
      "requiredFields": ["external_id", "name", "country"]
    },
    "transformationSettings": {
      "errorHandling": "default",
      "batchSize": 500,
      "timeout": 60000
    }
  }
}
```

## Error Responses

### Validation Error

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Mapping validation failed",
    "details": [
      {
        "mappingId": "3",
        "field": "email",
        "error": "Invalid email format"
      }
    ]
  }
}
```

### Transformation Error

```json theme={null}
{
  "success": false,
  "error": {
    "code": "TRANSFORMATION_ERROR",
    "message": "Error applying transformation",
    "details": {
      "mappingId": "4",
      "sourceField": "account_balance",
      "error": "Cannot multiply undefined by 1000"
    }
  }
}
```

## Best Practices

<AccordionGroup>
  <Accordion icon="bolt" title="Start Simple">
    * Begin with direct mappings for most fields
    * Add transformations only when necessary
    * Test each transformation individually
    * Gradually increase complexity
  </Accordion>

  <Accordion icon="vial" title="Testing">
    * Test mappings with sample data before production
    * Validate edge cases (null, empty, invalid values)
    * Monitor transformation errors in logs
    * Use strictMode in production environments
  </Accordion>

  <Accordion icon="shield" title="Data Quality">
    * Set appropriate defaultValue for optional fields
    * Use validationRule for complex validations
    * Apply format transformations for consistency
    * Handle missing/null values explicitly
  </Accordion>

  <Accordion icon="gauge" title="Performance">
    * Avoid complex custom transformations in hot paths
    * Use batch processing for large datasets
    * Set reasonable timeout values
    * Monitor transformation execution times
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Smart Field Detection" icon="wand-magic-sparkles" href="/api-reference/data-ingestion/custom-schemas">
    Auto-generate mappings from sample data
  </Card>

  <Card title="Import Entities" icon="upload" href="/api-reference/entities/create">
    Use mappings to import entity data
  </Card>

  <Card title="Data Mapping Guide" icon="book" href="/api-reference/data-ingestion/overview">
    Complete workflow guide
  </Card>

  <Card title="Transformations Guide" icon="arrow-right-arrow-left" href="/api-reference/data-ingestion/field-mappings">
    Advanced transformation patterns
  </Card>
</CardGroup>
