

# Creating an index
<a name="create-index"></a>

You can create an index using the console, or by calling the [CreateIndex](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateIndex.html) API. You can use the AWS Command Line Interface (AWS CLI) or SDK with the API. After you created your index, you can add documents directly to it or from a data source.

To create an index, you must provide the Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role for indexes to access CloudWatch. For more information, see [IAM roles for indexes](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html#iam-roles-index).

The following tabs provide a procedure for creating an index by using the AWS Management Console, and code examples for using the AWS CLI, and Python and Java SDKs.

------
#### [ Console ]

**To create an index**

1. Sign in to the AWS Management Console and open the Amazon Kendra console at [https://console.aws.amazon.com/kendra/](https://console.aws.amazon.com/kendra/).

1. Select **Create index** in the **Indexes** section.

1. In **Specify index details**, give your index a name and a description.

1. In **IAM role** provide an IAM role. To find a role, choose from roles in your account that contain the word "kendra" or enter the name of another role. For more information about the permissions that the role requires, see [IAM roles for indexes](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html#iam-roles-index).

1. Choose **Next**.

1. On the **Configure user access control** page, choose **Next**. You can update your index to use tokens for access control after you create an index. For more information, see [Controlling access to documents](https://docs.aws.amazon.com/kendra/latest/dg/create-index-access-control.html).

1. On the **Provisioning details** page, choose **Create**.

1. It might take some time for the index to create. Check the list of indexes to watch the progress of creating your index. When the status of the index is `ACTIVE`, your index is ready to use.

------
#### [ AWS CLI ]

**To create an index**

1. Use the following command to create an index. The `role-arn` must be the Amazon Resource Name (ARN) of an IAM role that can run Amazon Kendra actions. For more information, see [IAM roles](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html).

   The command is formatted for Linux and macOS. If you are using Windows, replace the Unix line continuation character (\$1) with a caret (^).

   ```
   aws kendra create-index \
    --name index name \
    --description "index description" \
    --role-arn arn:aws:iam::account ID:role/role name
   ```

1. It might take some time for the index to create. To check the state of your index, use the index ID returned by `create-index` with the following command. When the status of the index is `ACTIVE`, your index is ready to use.

   ```
   aws kendra describe-index \
    --index-id index ID
   ```

------
#### [ Python ]

**To create an index**
+ Provide values for the following variables in the code example that follows:
  + `description`—A description of the index that you're creating. This is optional.
  + `index_name`—The name of the index that you're creating.
  + `role_arn`—The Amazon Resource Name (ARN) of a role that can run Amazon Kendra APIs. For more information, see [IAM roles](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html).

  ```
  import boto3
  from botocore.exceptions import ClientError
  import pprint
  import time
  
  kendra = boto3.client("kendra")
  
  print("Create an index.")
  
  # Provide a name for the index
  index_name = "index-name"
  # Provide an optional description for the index
  description = "index description"
  # Provide the IAM role ARN required for indexes
  role_arn = "arn:aws:iam::${account id}:role/${role name}"
  
  try:
      index_response = kendra.create_index(
          Name = index_name,
          Description = description,
          RoleArn = role_arn
      )
  
      pprint.pprint(index_response)
  
      index_id = index_response["Id"]
  
      print("Wait for Amazon Kendra to create the index.")
  
      while True:
          # Get the details of the index, such as the status
          index_description = kendra.describe_index(
              Id = index_id
          )
          # If status is not CREATING, then quit
          status = index_description["Status"]
          print(" Creating index. Status: "+status)
          if status != "CREATING":
              break
          time.sleep(60)
  
  except  ClientError as e:
          print("%s" % e)
  
  print("Program ends.")
  ```

------
#### [ Java ]

**To create an index**
+ Provide values for the following variables in the code example that follows:
  + `description`—A description of the index that you're creating. This is optional.
  + `index_name`—The name of the index that you're creating.
  + `role_arn`—The Amazon Resource Name (ARN) of a role that can run Amazon Kendra APIs. For more information, see [IAM roles](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html).

  ```
  package com.amazonaws.kendra;
  
  import java.util.concurrent.TimeUnit;
  import software.amazon.awssdk.services.kendra.KendraClient;
  import software.amazon.awssdk.services.kendra.model.CreateIndexRequest;
  import software.amazon.awssdk.services.kendra.model.CreateIndexResponse;
  import software.amazon.awssdk.services.kendra.model.DescribeIndexRequest;
  import software.amazon.awssdk.services.kendra.model.DescribeIndexResponse;
  import software.amazon.awssdk.services.kendra.model.IndexStatus;
  
  
  public class CreateIndexExample {
  
      public static void main(String[] args) throws InterruptedException {
  
          String indexDescription = "Getting started index for Kendra";
          String indexName = "java-getting-started-index";
          String indexRoleArn = "arn:aws:iam::<your AWS account ID>:role/KendraRoleForGettingStartedIndex";
  
          System.out.println(String.format("Creating an index named %s", indexName));
          CreateIndexRequest createIndexRequest = CreateIndexRequest
              .builder()
              .description(indexDescription)
              .name(indexName)
              .roleArn(indexRoleArn)
              .build();
          KendraClient kendra = KendraClient.builder().build();
          CreateIndexResponse createIndexResponse = kendra.createIndex(createIndexRequest);
          System.out.println(String.format("Index response %s", createIndexResponse));
  
          String indexId = createIndexResponse.id();
  
          System.out.println(String.format("Waiting until the index with ID %s is created.", indexId));
          while (true) {
              DescribeIndexRequest describeIndexRequest = DescribeIndexRequest.builder().id(indexId).build();
              DescribeIndexResponse describeIndexResponse = kendra.describeIndex(describeIndexRequest);
              IndexStatus status = describeIndexResponse.status();
              if (status != IndexStatus.CREATING) {
                  break;
              }
  
              TimeUnit.SECONDS.sleep(60);
          }
  
          System.out.println("Index creation is complete.");
      }
  }
  ```

------

After you created your index, you add documents to it. You can add them directly or create a data source that updates your index on a regular schedule.

**Topics**
+ [Adding documents directly to an index with batch upload](in-adding-documents.md)
+ [Adding frequently asked questions (FAQs) to an index](in-creating-faq.md)
+ [Creating custom document fields](custom-attributes.md)
+ [Controlling user access to documents with tokens](create-index-access-control.md)

# Adding documents directly to an index with batch upload
<a name="in-adding-documents"></a>

You can add documents directly to an index using the [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) API. You can't add documents directly using the console. If you use the console, you connect to a data source to add documents to your index. Documents can be added from an S3 bucket or supplied as binary data. For a list of document types supported by Amazon Kendra see [Types of documents](https://docs.aws.amazon.com/kendra/latest/dg/index-document-types.html).

Adding documents to an index using `BatchPutDocument` is an asynchronous operation. After you call the `BatchPutDocument` API, you use the [BatchGetDocumentStatus](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchGetDocumentStatus) API to monitor the progress of indexing your documents. When you call the `BatchGetDocumentStatus` API with a list of document IDs, it returns the status of the document. When the status of the document is `INDEXED` or `FAILED`, processing of the document is complete. When the status is `FAILED`, the `BatchGetDocumentStatus` API returns the reason that the document couldn't be indexed.

If you want to alter your content and document metadata fields or attributes during the document ingestion process, see [Amazon Kendra Custom Document Enrichment](https://docs.aws.amazon.com/kendra/latest/dg/custom-document-enrichment.html). If you want to use a custom data source, each document you submit using the `BatchPutDocument` API requires a data source ID and execution ID as attributes or fields. For more information, see [Required attributes for custom data sources](https://docs.aws.amazon.com/kendra/latest/dg/data-source-custom.html#custom-required-attributes).

**Note**  
Each document ID must be unique per index. You cannot create a data source to index your documents with their unique IDs and then use the `BatchPutDocument` API to index the same documents, or vice versa. You can delete a data source and then use the `BatchPutDocument` API to index the same documents, or vice versa. Using the `BatchPutDocument` and `BatchDeleteDocument` APIs in combination with an Amazon Kendra data source connector for the same set of documents could cause inconsistencies with your data. Instead, we recommend using the [Amazon Kendra custom data source connector](https://docs.aws.amazon.com/kendra/latest/dg/data-source-custom.html).

The following developer guide documents show how to add documents directly to an index.

**Topics**
+ [Adding documents with the BatchPutDocument API](#in-adding-binary-doc)
+ [Adding documents from an S3 bucket](#in-adding-plain-text)

## Adding documents with the BatchPutDocument API
<a name="in-adding-binary-doc"></a>

The following example adds a blob of text to an index by calling [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument). You can use the `BatchPutDocument` API to add documents directly to your index. For a list of document types supported by Amazon Kendra see [Types of documents](https://docs.aws.amazon.com/kendra/latest/dg/index-document-types.html).

For an example of creating an index using the AWS CLI and SDKs, see [Creating an index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html). To set up the CLI and SDKs, see [Setting up Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/setup.html).

**Note**  
Files added to the index must be in a UTF-8 encoded byte stream.

In the following examples, UTF-8 encoded text is added to the index.

------
#### [ CLI ]

In the AWS Command Line Interface, use the following command. The command is formatted for Linux and macOS. If you are using Windows, replace the Unix line continuation character (\$1) with a caret (^).

```
aws kendra batch-put-document \
   --index-id index-id \
   --documents '{"Id":"doc-id-1", "Blob":"Amazon.com is an online retailer.", "ContentType":"PLAIN_TEXT", "Title":"Information about Amazon.com"}'
```

------
#### [ Python ]

```
import boto3

kendra = boto3.client("kendra")

# Provide the index ID
index_id = "index-id"

# Provide the title and text
title = "Information about Amazon.com"
text = "Amazon.com is an online retailer."

document = {
    "Id": "1",
    "Blob": text,
    "ContentType": "PLAIN_TEXT",
    "Title": title
}

documents = [
    document
]

result = kendra.batch_put_document(
    IndexId = index_id,
    Documents = documents
)

print(result)
```

------
#### [ Java ]

```
package com.amazonaws.kendra;


import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.BatchPutDocumentRequest;
import software.amazon.awssdk.services.kendra.model.BatchPutDocumentResponse;
import software.amazon.awssdk.services.kendra.model.ContentType;
import software.amazon.awssdk.services.kendra.model.Document;

public class AddDocumentsViaAPIExample {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();

        String indexId = "yourIndexId";

        Document testDoc = Document
            .builder()
            .title("The title of your document")
            .id("a_doc_id")
            .blob(SdkBytes.fromUtf8String("your text content"))
            .contentType(ContentType.PLAIN_TEXT)
            .build();

        BatchPutDocumentRequest batchPutDocumentRequest = BatchPutDocumentRequest
            .builder()
            .indexId(indexId)
            .documents(testDoc)
            .build();

        BatchPutDocumentResponse result = kendra.batchPutDocument(batchPutDocumentRequest);

        System.out.println(String.format("BatchPutDocument Result: %s", result));
    }
}
```

------

## Adding documents from an S3 bucket
<a name="in-adding-plain-text"></a>

You can add documents directly to your index from an Amazon S3 bucket using the [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument) API. You can add up to 10 documents in the same call. When you use an S3 bucket, you must provide an IAM role with permission to access the bucket that contains your documents. You specify the role in the `RoleArn` parameter.

Using the [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument) API to add documents from an Amazon S3 bucket is a one-time operation. To keep an index synchronized with the contents of a bucket, create an Amazon S3 data source. For more information, see [Amazon S3 data source](https://docs.aws.amazon.com/kendra/latest/dg/data-source-s3.html).

For an example of creating an index using the AWS CLI and SDKs, see [Creating an index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html). To set up the CLI and SDKs, see [Setting up Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/setup.html). For information on creating an S3 bucket, see [Amazon Simple Storage Service documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html).

In the following example, two Microsoft Word documents are added to the index using the `BatchPutDocument` API.

------
#### [ Python ]

```
import boto3

kendra = boto3.client("kendra")

# Provide the index ID
index_id = "index-id"
# Provide the IAM role ARN required to index documents in an S3 bucket
role_arn = "arn:aws:iam::${acccountID}:policy/${roleName}"

doc1_s3_file_data = {
    "Bucket": "bucket-name",
    "Key": "document1.docx"
}

doc1_document = {
    "S3Path": doc1_s3_file_data,
    "Title": "Document 1 title",
    "Id": "doc_1"
}

doc2_s3_file_data = {
    "Bucket": "bucket-name",
    "Key": "document2.docx"
}

doc2_document = {
    "S3Path": doc2_s3_file_data,
    "Title": "Document 2 title",
    "Id": "doc_2"
}

documents = [
    doc1_document,
    doc2_document
]

result = kendra.batch_put_document(
    Documents = documents,
    IndexId = index_id,
    RoleArn = role_arn
)

print(result)
```

------
#### [ Java ]

```
package com.amazonaws.kendra;

import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.BatchPutDocumentRequest;
import software.amazon.awssdk.services.kendra.model.BatchPutDocumentResponse;
import software.amazon.awssdk.services.kendra.model.Document;
import software.amazon.awssdk.services.kendra.model.S3Path;

public class AddFilesFromS3Example {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();

        String indexId = "yourIndexId";
        String roleArn = "yourIndexRoleArn";

        Document pollyDoc = Document
            .builder()
            .s3Path(
                S3Path.builder()
                .bucket("amzn-s3-demo-bucket")
                .key("What is Amazon Polly.docx")
                .build())
            .title("What is Amazon Polly")
            .id("polly_doc_1")
            .build();

        Document rekognitionDoc = Document
            .builder()
            .s3Path(
                S3Path.builder()
                .bucket("amzn-s3-demo-bucket")
                .key("What is Amazon Rekognition.docx")
                .build())
            .title("What is Amazon rekognition")
            .id("rekognition_doc_1")
            .build();

        BatchPutDocumentRequest batchPutDocumentRequest = BatchPutDocumentRequest
            .builder()
            .indexId(indexId)
            .roleArn(roleArn)
            .documents(pollyDoc, rekognitionDoc)
            .build();

        BatchPutDocumentResponse result = kendra.batchPutDocument(batchPutDocumentRequest);

        System.out.println(String.format("BatchPutDocument result: %s", result));
    }
}
```

------

# Adding frequently asked questions (FAQs) to an index
<a name="in-creating-faq"></a>

**Note**  
Feature support varies by index type and search API being used. To see if this feature is supported for the index type and search API you’re using, see [Index types](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html).

You can add frequently asked questions (FAQs) directly to your index using the console or the [CreateFaq](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateFaq.html) API. Adding FAQs to an index is an asynchronous operation. You put the data for the FAQ in a file that you store in an Amazon Simple Storage Service bucket. You can use CSV or JSON files as input for your FAQ:
+ Basic CSV—A CSV file where each row contains a question, answer, and an optional source URI.
+ Custom CSV—A CSV file that contains questions, answers, and headers for custom fields/attributes that you can use to facet, display, or sort FAQ responses. You can also define access control fields to limit the FAQ response to certain users and groups that are allowed to see the FAQ response.
+ JSON—A JSON file that contains questions, answers, and custom fields/attributes that you can use to facet, display, or sort FAQ responses. You can also define access control fields to limit the FAQ response to certain users and groups that are allowed to see the FAQ response.

For example, the following is a basic CSV file that provides answers to questions about free clinics in Spokane, Washington USA and Mountain View, Missouri, USA.

```
How many free clinics are in Spokane WA?, 13
How many free clinics are there in Mountain View Missouri?, 7
```

**Note**  
The FAQ file must be a UTF-8-encoded file.

**Topics**
+ [Creating index fields for an FAQ file](#in-custom-fields-faq)
+ [Basic CSV file](#faq-basic-csv)
+ [Custom CSV file](#faq-custom-csv)
+ [JSON file](#faq-custom-json)
+ [Using your FAQ file](#using-faq-file)
+ [FAQ files in languages other than English](#faq-languages)

## Creating index fields for an FAQ file
<a name="in-custom-fields-faq"></a>

**Note**  
Feature support varies by index type and search API being used. To see if this feature is supported for the index type and search API you’re using, see [Index types](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html).

When you use a [custom CSV](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html#faq-custom-csv) or [JSON](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html#faq-custom-json) file for input, you can declare custom fields for your FAQ questions. For example, you can create a custom field that assigns each FAQ question a business department. When the FAQ is returned in a response, you can use the department as a facet to narrow the search to "HR" or "Finance" only, for example.

A custom field must map to an index field. In the console, you use the **Facet definition** page to create an index field. When using the API, you must first create an index field using the [UpdateIndex](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateIndex.html) API.

The field/attribute type in the FAQ file must match the type of the associated index field. For example, the "Department" field is a `STRING_LIST` type field. So, you must provide values for the department field as a string list in your FAQ file. You can check the type of index fields using the **Facet definition** page in the console or by using the [DescribeIndex](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeIndex.html) API.

When you create an index field that maps to a custom attribute, you can mark it displayable, facetable, or sortable. You can't make a custom attribute searchable.

In addition to the custom attributes, you can also use the Amazon Kendra reserved or common fields in a custom CSV or JSON file. For more information, see [Document attributes or fields](https://docs.aws.amazon.com/kendra/latest/dg/hiw-document-attributes.html).

## Basic CSV file
<a name="faq-basic-csv"></a>

Use a basic CSV file when you want to use a simple structure for your FAQs. In a basic CSV file, each row has two or three fields: a question, an answer, and an optional source URI that points to a document with more information.

The contents of the file must follow the [RFC 4180 Common Format and MIME Type for Comma-Separated Values (CSV) Files](https://tools.ietf.org/html/rfc4180).

The following is a FAQ file in the basic CSV format.

```
How many free clinics are in Spokane WA?, 13, https://s3.region.company.com/bucket-name/directory/faq.csv
How many free clinics are there in Mountain View Missouri?, 7, https://s3.region.company.com/bucket-name/directory/faq.csv
```

## Custom CSV file
<a name="faq-custom-csv"></a>

Use a custom CSV file when you want to add custom fields/attributes to your FAQ questions. For a custom CSV file, you use a header row in your CSV file to define the additional attributes.

The CSV file must contain the following two required fields:
+ `_question`—The frequently asked question
+ `_answer`—The answer to the frequently asked question

Your custom CSV file can contain both Amazon Kendra reserved fields (except `_faq_id`, `_data_source_id`, `_document_title`, and `_file_type`) and any custom fields. 

 The following is an example of a custom CSV file.

```
_question,_answer,_last_updated_at,custom_string
How many free clinics are in Spokane WA?, 13, 2012-03-25T12:30:10+01:00, Note: Some free clinics require you to meet certain criteria in order to use their services
How many free clinics are there in Mountain View Missouri?, 7, 2012-03-25T12:30:10+01:00, Note: Some free clinics require you to meet certain criteria in order to use their services
```

The contents of the custom file must follow the [RFC 4180 Common Format and MIME Type for Comma-Separated Values (CSV) Files](https://tools.ietf.org/html/rfc4180).

The following lists the types of custom fields:
+ Date—ISO 8601-encoded date and time values.

  For example, 2012-03-25T12:30:10\$101:00 is the ISO 8601 date-time format for March 25, 2012, at 12:30PM (plus 10 seconds) in the Central European Time time zone.
+ Long—Numbers, such as `1234`.
+ String—String values. If your string contains commas, enclose the entire value in double quotation marks (") (for example, `"custom attribute, and more"`).
+ String list—A list of string values. List the values in a comma-separated list that's enclosed in quotation marks (") (for example, `"item1, item2, item3"`). If the list contains only a single entry, you can omit the quotation marks (for example, `item1`).

A custom CSV file can contain user access control fields. You can use these fields to limit access to the FAQ to certain users and groups. To filter on user context, the user must provide user and group information in the query. Otherwise, all relevant FAQs are returned. For more information, see [User context filtering](https://docs.aws.amazon.com/kendra/latest/dg/user-context-filter.html).

There following lists the user context filters for FAQs:
+ `_acl_user_allow`—Users in the allow list can see the FAQ in the query response. The FAQ isn't returned to other users.
+ `_acl_user_deny`—Users in the deny list can't see the FAQ in the query response. The FAQ is returned to all other users when it's relevant to the query.
+ `_acl_group_allow`—Users that are members of an allowed group can see the FAQ in the query response. The FAQ isn't returned to users that are members of another group.
+ `_acl_group_deny`—Users that are members of a denied group can't see the FAQ in the query response. The FAQ is returned to other groups when it's relevant to the query.

Provide the values for the allow and deny lists in comma-separated lists enclosed in quotation marks (for example, `"user1,user2,user3"`). You can include a user or a group in either an allow list or a deny list, but not both where the same user is individually allowed but also group denied. If you include a user or group in both, you receive an error.

The following is an example of a custom CSV file with user context information.

```
_question, _answer, _acl_user_allow, _acl_user_deny, _acl_group_allow, _acl_group_deny
How many free clinics are in Spokane WA?, 13, "userID6201,userID7552", "userID1001,userID2020", groupBasicPlusRate, groupPremiumRate
```

## JSON file
<a name="faq-custom-json"></a>

You can use a JSON file to provide questions, answers, and fields for your index. You can add any of the Amazon Kendra reserved fields or custom fields to the FAQ.

The following is the schema for the JSON file.

```
{
    "SchemaVersion": 1,
    "FaqDocuments": [
        {
            "Question": string,
            "Answer": string,
            "Attributes": {
                string: object
                additional attributes
            },
            "AccessControlList": [
               {
                   "Name": string,
                   "Type": enum( "GROUP" | "USER" ),
                   "Access": enum( "ALLOW" | "DENY" )
               },
               additional user context
            ]
        },
        additional FAQ documents
    ]
}
```

The following example JSON file shows two FAQ documents. One of the documents has the required question and answer only. The other document also includes additional field and user context or access control information.

```
{
    "SchemaVersion": 1,
    "FaqDocuments": [
        {
            "Question": "How many free clinics are in Spokane WA?",
            "Answer": "13"
        },
        {
            "Question": "How many free clinics are there in Mountain View Missouri?",
            "Answer": "7",
            "Attributes": {
                "_source_uri": "https://s3.region.company.com/bucket-name/directory/faq.csv",
                "_category": "Charitable Clinics"
            },
            "AccessControlList": [
               {
                   "Name": "user@amazon.com",
                   "Type": "USER",
                   "Access": "ALLOW"
               },
               {
                   "Name": "Admin",
                   "Type": "GROUP",
                   "Access": "ALLOW"
               }
            ]
        }
    ]
}
```

The following lists the types of custom fields:
+ Date—A JSON string value with ISO 8601-encoded date and time values. For example, 2012-03-25T12:30:10\$101:00 is the ISO 8601 date-time format for March 25, 2012, at 12:30PM (plus 10 seconds) in the Central European Time time zone.
+ Long—A JSON number value, such as `1234`.
+ String—A JSON string value (for example, `"custom attribute"`).
+ String list—A JSON array of string values (for example, `["item1,item2,item3"]`).

A JSON file can contain user access control fields. You can use these fields to limit access to the FAQ to certain users and groups. To filter on user context, the user must provide user and group information in the query. Otherwise, all relevant FAQs are returned. For more information, see [User context filtering](https://docs.aws.amazon.com/kendra/latest/dg/user-context-filter.html).

You can include a user or a group in either an allow list or a deny list, but not both where the same user is individually allowed but also group denied. If you include a user or group in both, you receive an error.

The following is an example of including user access control to a JSON FAQ.

```
"AccessControlList": [
                {
                    "Name": "group or user name",
                    "Type": "GROUP | USER",
                    "Access": "ALLOW | DENY"
                },
                additional user context
            ]
```

## Using your FAQ file
<a name="using-faq-file"></a>

After you store your FAQ input file in an S3 bucket, you use the console or the `CreateFaq` API to put the questions and answers into your index. If you want to update a FAQ, delete the FAQ and create it again. You use the `DeleteFaq` API to delete a FAQ.

You must provide an IAM role that has access to the S3 bucket that contains your source files. You specify the role in the console or in the `RoleArn` parameter. The following is an example of adding a FAQ file to an index.

------
#### [ Python ]

```
import boto3

kendra = boto3.client("kendra")

# Provide the index ID
index_id = "index-id"
# Provide the IAM role ARN required to index documents in an S3 bucket
role_arn = "arn:aws:iam::${accountId}:role/${roleName}"

# Provide the S3 bucket path information to the FAQ file
faq_path = {
    "Bucket": "bucket-name",
    "Key": "FreeClinicsUSA.csv"
}

response = kendra.create_faq(
    S3Path =  faq_path,
    Name = "FreeClinicsUSA",
    IndexId = index_id,
    RoleArn = role_arn
)

print(response)
```

------
#### [ Java ]

```
package com.amazonaws.kendra;

import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.CreateFaqRequest;
import software.amazon.awssdk.services.kendra.model.CreateFaqResponse;
import software.amazon.awssdk.services.kendra.model.S3Path;

public class AddFaqExample {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();

        String indexId = "yourIndexId";
        String roleArn = "your role for accessing S3 files";

        CreateFaqRequest createFaqRequest = CreateFaqRequest
            .builder()
            .indexId(indexId)
            .name("FreeClinicsUSA")
            .roleArn(roleArn)
            .s3Path(
                S3Path
                    .builder()
                    .bucket("amzn-s3-demo-bucket")
                    .key("FreeClinicsUSA.csv")
                    .build())
            .build();

        CreateFaqResponse response = kendra.createFaq(createFaqRequest);

        System.out.println(String.format("The result of creating FAQ: %s", response));

    }
}
```

------

## FAQ files in languages other than English
<a name="faq-languages"></a>

You can index a FAQ in a supported language. Amazon Kendra indexes FAQs in English by default if you don't specify a language. You specify the language code when you call the [CreateFaq](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateFaq.html) operation or you can include the language code for a FAQ in the FAQ metadata as a field. If a FAQ doesn't have a language code in its metadata specified in a metadata field, the FAQ is indexed using the language code specified when you call the `CreateFAQ` operation. To index a FAQ document in a supported language in the console, go to **FAQs** and select **Add FAQ**. You choose a language from the dropdown **Language**.

# Creating custom document fields
<a name="custom-attributes"></a>

**Note**  
Feature support varies by index type and search API being used. To see if this feature is supported for the index type and search API you’re using, see [Searching indexes](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index.html#index-searching).

You can create custom attributes or fields for your documents in your Amazon Kendra index. For example, you can create a custom field or attribute called "Department" with the values of "HR", "Sales", and "Manufacturing". If you map these custom fields or attributes to your Amazon Kendra index, you can use them to filter the search results to include documents by the "HR" department attribute, for example.

Before you can use a custom field or attribute, you must first create the field in the index. Use the console to edit the data source field mappings to add a custom field or use the [UpdateIndex](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateIndex.html) API to create the index field. You cannot change the field data type once you have created the field.

For most data sources, you map fields in the external data source to the corresponding fields in Amazon Kendra. For more information, see [Mapping data source fields](https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html). For S3 data sources, you can create custom fields or attributes using a JSON metadata file.

You can create up to 500 custom fields or attributes.

You can also use Amazon Kendra reserved or common fields. For more information, see [Document attributes or fields](https://docs.aws.amazon.com/kendra/latest/dg/hiw-document-attributes.html).

**Topics**
+ [Updating custom document fields](#update-attributes)

## Updating custom document fields
<a name="update-attributes"></a>

With the `UpdateIndex` API, you add custom fields or attributes using the `DocumentMetadataConfigurationUpdates` parameter.

The following JSON example uses `DocumentMetadataConfigurationUpdates` to add a field called "Department" to the index.

```
"DocumentmetadataConfigurationUpdates": [
   {
       "Name": "Department",
       "Type": "STRING_VALUE"
   }
]
```

The following sections include examples for adding custom attributes or fields using the [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) and for an Amazon S3 data source.

**Topics**
+ [Adding custom attributes or fields with the BatchPutDocument API](#custom-attributes-batch)
+ [Adding custom attributes or fields to an Amazon S3 data source](#custom-attributes-s3)

### Adding custom attributes or fields with the BatchPutDocument API
<a name="custom-attributes-batch"></a>

When you use the [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) API to add a document to your index, you specify custom fields or attributes as part of `Attributes`. You can add multiple fields or attributes when you call the API. You can create up to 500 custom fields or attributes. The following example is a custom field or attribute that adds "Department" to a document.

```
"Attributes": 
    {
        "Department": "HR",
        "_category": "Vacation policy"
    }
```

### Adding custom attributes or fields to an Amazon S3 data source
<a name="custom-attributes-s3"></a>

When you use an S3 bucket as a data source for your index, you add metadata to the documents with companion metadata files. You place the metadata JSON files in a directory structure that is parallel to your documents. For more information, see [S3 document metadata](https://docs.aws.amazon.com/kendra/latest/dg/s3-metadata.html).

You specify custom fields or attributes in the `Attributes` JSON structure. You can create up to 500 custom fields or attributes. For example, the following example uses `Attributes` to define three custom fields or attributes and one reserved field.

```
"Attributes": {
        "brand": "Amazon Basics",
        "price": 1595,
        "_category": "sports",
        "subcategories": ["outdoors", "electronics"]
    }
```

The following steps walk you through adding custom attributes to an Amazon S3 data source.

**Topics**
+ [Step 1: Create a Amazon Kendra index](#custom-attributes-s3-1)
+ [Step 2: Update index to add custom document fields](#custom-attributes-s3-2)
+ [Step 3: Create an Amazon S3 data source and map data source fields to custom attributes](#custom-attributes-s3-3)

#### Step 1: Create a Amazon Kendra index
<a name="custom-attributes-s3-1"></a>

Follow the steps in [Creating an index](create-index.md) to create your Amazon Kendra index.

#### Step 2: Update index to add custom document fields
<a name="custom-attributes-s3-2"></a>

After creating an index, you add fields to it. The following procedure shows how to add fields to an index using the console and the CLI.

------
#### [ Console ]

**To create index fields**

1. Make sure you've [created an index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html).

1. Then, from the left navigation menu, from **Data management**, choose **Facet definition**.

1. In **Index field settings guide**, from **Index fields**, choose **Add field** to add custom fields.

1. In the **Add index field** dialog box, do the following:
   + **Field name** – Add a field name.
   + **Data type** – Select data type, whether **String**, **String list**, or **Date**.
   + **Usage types** – Select usage types, whether **Facetable**, **Searchable**, **Displayable**, and **Sortable**.

     Then, select **Add**.

   Repeat the last step for any other fields you want to map.

------
#### [ CLI ]

```
aws kendra update-index  \
--region $region \
--endpoint-url $endpoint \
--application-id $applicationId \
--index-id $indexId  \
--document-metadata-configuration-updates \
"[
    {
        "Name": "string",
        "Type": "STRING_VALUE"|"STRING_LIST_VALUE"|"LONG_VALUE"|"DATE_VALUE",
        "Relevance": {
            "Freshness": true|false,
            "Importance": integer,
            "Duration": "string",
            "RankOrder": "ASCENDING"|"DESCENDING",
            "ValueImportanceMap": {"string": integer
            ...}
    },
    "Search": {
        "Facetable": true|false,
        "Searchable": true|false,
        "Displayable": true|false,
        "Sortable": true|false
        }
    }
...
]"
```

------

#### Step 3: Create an Amazon S3 data source and map data source fields to custom attributes
<a name="custom-attributes-s3-3"></a>

To create an Amazon S3 data source and map fields to it, follow the instructions in [Amazon S3](data-source-s3.md).

If you're using the API, use the `fieldMappings` attribute under `configuration` when you use the [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API.

For an overview of how data source fields are mapped, see [Mapping data source fields](field-mapping.md).

# Controlling user access to documents with tokens
<a name="create-index-access-control"></a>

**Note**  
Feature support varies by index type and search API being used. To see if this feature is supported for the index type and search API you’re using, see [Index types](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html).

**Important**  
Amazon Kendra GenAI Enterprise Edition indices don't support token-based user access control.

You can control which users or groups can access certain documents in your index or see certain documents in their search results. This is called user context filtering. It is a kind of personalized search with the benefit of controlling access to documents. For example, not all teams that search the company portal for information should access top-secret company documents, nor are these documents relevant to all users. Only specific users or groups of teams given access to top-secret documents should see these documents in their search results.

Amazon Kendra Enterprise and Developer indices support token-based user access control using the following token types:
+ Open ID
+ JWT with a shared secret
+ JWT with a public key
+ JSON

Amazon Kendra can be used to deliver secure enterprise search for your retrieval and search applications. During query and retrieval, Amazon Kendra filters search results based on `AttributeFilters` and `UserContext` provided in the request. Amazon Kendra reads document access control lists (ACLs) collected by the its connectors during crawl and ingestion. The retrieval and search results return URLs pointing back to the original document repositories plus short excerpts. Access to the full document is still enforced by the original repository.

**Topics**
+ [Using OpenID](create-index-access-control-tokens-openid.md)
+ [Using a JSON Web Token (JWT) with a shared secret](create-index-access-control-tokens-jwtshared.md)
+ [Using a JSON Web Token (JWT) with a public key](create-index-access-control-tokens-jwtpublic.md)
+ [Using JSON](create-index-access-control-tokens-json.md)

# Using OpenID
<a name="create-index-access-control-tokens-openid"></a>

To configure an Amazon Kendra index to use an OpenID token for access control, you need the JWKS (JSON Web Key Set) URL from the OpenID provider. In most cases the JWKS URL is in the following format (if they're following openId discovery) `https://domain-name/.well_known/jwks.json`. 

The following examples show how to use an OpenID token for user access control when you create an index.

------
#### [ Console ]

1. Choose **Create index** to start creating a new index.

1. On the **Specify index details** page, give your index a name and a description. 

1. For **IAM role**, select a role or select **Create a new role** to and specify a role name to create a new role. The IAM role will have the prefix "AmazonKendra-". 

1. Leave all of the other fields at their defaults. Choose **Next**.

1. In the **Configure user access control** page, under **Access control settings**, choose **Yes** to use tokens for access control. 

1. Under **Token configuration**, select **OpenID** as the **Token type**. 

1. Specify a **Signing key URL**. The URL should point to a set of JSON web keys. 

1. *Optional* Under **Advanced configuration**: 

   1. Specify a **Username** to use in the ACL check. 

   1. Specify one or more **Groups** to use in the ACL check. 

   1. Specify the **Issuer** that will validate the token issuer. 

   1. Specify the **Client Id(s)**. You must specify a regular expression that match the audience in the JWT.

1. In the **Provisioning details** page, choose **Developer edition**.

1. Choose **Create** to create your index.

1. Wait for your index to be created. Amazon Kendra provisions the hardware for your index. This operation can take some time.

------
#### [ CLI ]

To create an index with the AWS CLI using a JSON input file, first create a JSON file with your desired parameters:

```
{
    "Name": "user-context",
    "Edition": "ENTERPRISE_EDITION",
    "RoleArn": "arn:aws:iam::account-id:role:/my-role",
    "UserTokenConfigurations": [
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "URL",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "URL": "https://example.com/.well-known/jwks.json"
            }
        }
    ],
    "UserContextPolicy": "USER_TOKEN"
}
```

You can override the default user and group field names. The default value for `UserNameAttributeField` is "user". The default value for `GroupAttributeField` is "groups". 

Next, call `create-index` using the input file. For example, if the name of your JSON file is `create-index-openid.json`, you can use the following: 

```
aws kendra create-index --cli-input-json file://create-index-openid.json
```

------
#### [ Python ]

```
response = kendra.create_index(
    Name='user-context',
    Edition='ENTERPRISE_EDITION',
    RoleArn='arn:aws:iam::account-id:role:/my-role',
    UserTokenConfigurations=[
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "URL",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "URL": "https://example.com/.well-known/jwks.json"
            }
        }
    ],
    UserContextPolicy='USER_TOKEN'
)
```

------

# Using a JSON Web Token (JWT) with a shared secret
<a name="create-index-access-control-tokens-jwtshared"></a>

The following examples show how to use JSON Web Token (JWT) with a shared secret token for user access control when you create an index. 

------
#### [ Console ]

1. Choose **Create index** to start creating a new index.

1. On the **Specify index details** page, give your index a name and a description.

1. For **IAM role**, select a role or select **Create a new role** to and specify a role name to create a new role. The IAM role will have the prefix "AmazonKendra-".

1. Leave all of the other fields at their defaults. Choose **Next**.

1. In the **Configure user access control** page, under **Access control settings**, choose **Yes** to use tokens for access control.

1. Under **Token configuration**, select **JWT with shared secret** as the **Token type**.

1. Under **Parameters for signing shared secret**, choose the **Type of secret**. You can use an existing AWS Secrets Manager shared secret or create a new shared secret.

   To create a new shared secret, choose **New** and then follow these steps:

   1. Under **New AWS Secrets Manager secret**, specify a **Secret name**. The prefix `AmazonKendra-` will be added when you save the public key.

   1. Specify a **Key ID**. The key id is a hint that indicates which key was used to secure the JSON web signature of the token.

   1. Choose the signing **Algorithm** for the token. This is the cryptographic algorithm used to secure the ID token. For more information on RSA, see [RSA Cryptography](https://tools.ietf.org/html/rfc3447).

   1. Specify a **Shared secret** by entering a base64 URL encoded secret. You can also select **Generate secret** to have a secret generated for you. You must ensure the secret is a base64 URL encoded secret.

   1. (*Optional*) Specify when the shared secret is valid. You can specify the date and time a secret is valid from, valid to, or both. The secret will be valid in the interval specified.

   1. Select **Save secret** to save the new secret.

1. (*Optional*) Under **Advanced configuration**:

   1. Specify a **Username** to use in the ACL check.

   1. Specify one or more **Groups** to use in the ACL check.

   1. Specify the **Issuer** that will validate the token issuer.

   1. Specify the **Claim ID(s)**. You must specify a regular expression that matches the audience in the JWT.

1. In the **Provisioning details** page, choose **Developer edition**.

1. Choose **Create** to create your index.

1. Wait for your index to be created. Amazon Kendra provisions the hardware for your index. This operation can take some time.

------
#### [ CLI ]

You can use JWT token with a shared secret inside of AWS Secrets Manager. The secret must be a base64 URL encoded secret. You need the Secrets Manager ARN, and your Amazon Kendra role must have access to `GetSecretValue` on the Secrets Manager resource. If you are encrypting the Secrets Manager resource with AWS KMS, the role must also have access to the decrypt action.

To create an index with the AWS CLI using a JSON input file, first create a JSON file with your desired parameters: 

```
{
    "Name": "user-context",
    "Edition": "ENTERPRISE_EDITION",
    "RoleArn": "arn:aws:iam::account-id:role:/my-role",
    "UserTokenConfigurations": [
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "SECRET_MANAGER",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "SecretManagerArn": "arn:aws:secretsmanager:us-west-2:account id:secret:/my-user-context-secret
            }
        }
    ],    
    "UserContextPolicy": "USER_TOKEN"
}
```

You can override the default user and group field names. The default value for `UserNameAttributeField` is "user". The default value for `GroupAttributeField` is "groups". 

Next, call `create-index` using the input file. For example, if the name of your JSON file is `create-index-openid.json`, you can use the following: 

```
aws kendra create-index --cli-input-json file://create-index-openid.json
```

The secret must have the following format in AWS Secrets Manager:

```
{
  "keys": [
    {
      "kid": "key_id",
      "alg": "HS256|HS384|HS512",
      "kty": "OCT", 
      "use": "sig", //this value can be sig only for now
      "k": "secret",
      "nbf":"ISO1806 date format"
      "exp":"ISO1806 date format"
    }
  ]
}
```

For more information about JWT, see [jwt.io](http://jwt.io).

------
#### [ Python ]

You can use JWT token with a shared secret inside of AWS Secrets Manager. The secret must be a base64 URL encoded secret. You need the Secrets Manager ARN, and your Amazon Kendra role must have access to `GetSecretValue` on the Secrets Manager resource. If you are encrypting the Secrets Manager resource with AWS KMS, the role must also have access to the decrypt action.

```
response = kendra.create_index(
    Name='user-context',
    Edition='ENTERPRISE_EDITION',
    RoleArn='arn:aws:iam::account-id:role:/my-role',
    UserTokenConfigurations=[
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "URL",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "SecretManagerArn": "arn:aws:secretsmanager:us-west-2:account id:secret:/my-user-context-secret"
            }
        }
    ],
    UserContextPolicy='USER_TOKEN'
)
```

------

# Using a JSON Web Token (JWT) with a public key
<a name="create-index-access-control-tokens-jwtpublic"></a>

The following examples show how to use JSON Web Token (JWT) with a public key for user access control when you create an index. For more information about JWT, see [jwt.io](http://jwt.io).

------
#### [ Console ]

1. Choose **Create index** to start creating a new index.

1. On the **Specify index details** page, give your index a name and a description. 

1. For **IAM role**, select a role or select **Create a new role** to and specify a role name to create a new role. The IAM role will have the prefix "AmazonKendra-".

1. Leave all of the other fields at their defaults. Choose **Next**.

1. In the **Configure user access control** page, under **Access control settings**, choose **Yes** to use tokens for access control.

1. Under **Token configuration**, select **JWT with public key** as the **Token type**.

1. Under **Parameters for signing public key**, choose the **Type of secret**. You can use an existing AWS Secrets Manager secret or create a new secret.

   To create a new secret, choose **New** and then follow these steps:

   1. Under **New AWS Secrets Manager secret**, specify a **Secret name**. The prefix `AmazonKendra-` will be added when you save the public key.

   1. Specify a **Key ID**. The key id is a hint that indicates which key was used to secure the JSON web signature of the token.

   1. Choose the signing **Algorithm** for the token. This is the cryptographic algorithm used to secure the ID token. For more information on RSA, see [RSA Cryptography](https://tools.ietf.org/html/rfc3447).

   1. Under **Certificate attributes**, specify an *optional* **Certificate chain**. The certificate chain is made up of a list of certificates. It begins with a server’s certificate and terminates with the root certificate.

   1. *Optional* Specify the **Thumbprint or fingerprint**. It should be is a hash of a certificate, computed over all certificate data and its signature.

   1. Specify the **Exponent**. This is the exponent value for the RSA public key. It is represented as a Base64urlUInt-encoded value.

   1. Specify the **Modulus**. This is the exponent value for the RSA public key. It is represented as a Base64urlUInt-encoded value.

   1. Select **Save key** to save the new key.

1. *Optional* Under **Advanced configuration**:

   1. Specify a **Username** to use in the ACL check.

   1. Specify one or more **Groups** to use in the ACL check.

   1. Specify the **Issuer** that will validate the token issuer.

   1. Specify the **Client Id(s)**. You must specify a regular expression that match the audience in the JWT.

1. In the **Provisioning details** page, choose **Developer edition**.

1. Choose **Create** to create your index.

1. Wait for your index to be created. Amazon Kendra provisions the hardware for your index. This operation can take some time.

------
#### [ CLI ]

You can use JWT with a public key inside of a AWS Secrets Manager. You need the Secrets Manager ARN, and your Amazon Kendra role must have access to `GetSecretValue` on the Secrets Manager resource. If you are encrypting the Secrets Manager resource with AWS KMS, the role must also have access to the decrypt action.

To create an index with the AWS CLI using a JSON input file, first create a JSON file with your desired parameters:

```
{
    "Name": "user-context",
    "Edition": "ENTERPRISE_EDITION",
    "RoleArn": "arn:aws:iam::account id:role:/my-role",
    "UserTokenConfigurationList": [
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "SECRET_MANAGER",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "SecretManagerArn": "arn:aws:secretsmanager:us-west-2:account id:secret:/my-user-context-secret
            }
        }
    ],    "UserContextPolicy": "USER_TOKEN"
}
```

You can override the default user and group field names. The default value for `UserNameAttributeField` is "user". The default value for `GroupAttributeField` is "groups".

Next, call `create-index` using the input file. For example, if the name of your JSON file is `create-index-openid.json`, you can use the following:

```
aws kendra create-index --cli-input-json file://create-index-openid.json
```

The secret must have the following format in Secrets Manager:

```
{
  "keys": [
    {
      "alg": "RS256|RS384|RS512",
      "kty": "RSA", //this can be RSA only for now
      "use": "sig", //this value can be sig only for now
      "n": "modulus of standard pem",
      "e": "exponent of standard pem",
      "kid": "key_id",
      "x5t": "certificate thumprint for x.509 cert",
      "x5c": [
        "certificate chain"
      ]
    }
  ]
}
```

For more information about JWT, see [jwt.io](http://jwt.io).

------
#### [ Python ]

```
response = kendra.create_index(
    Name='user-context',
    Edition='ENTERPRISE_EDITION',
    RoleArn='arn:aws:iam::account id:role:/my-role',
    UserTokenConfigurationList=[
        {
            "JwtTokenTypeConfiguration": {
                "KeyLocation": "URL",
                "Issuer": "optional: specify the issuer url",
                "ClaimRegex": "optional: regex to validate claims in the token",
                "UserNameAttributeField": "optional: user",
                "GroupAttributeField": "optional: group",
                "SecretManagerArn": "arn:aws:secretsmanager:us-west-2:account id:secret:/my-user-context-secret"
            }
        }
    ],
    UserContextPolicy='USER_TOKEN'
)
```

------

# Using JSON
<a name="create-index-access-control-tokens-json"></a>

The following examples show how to use JSON for user access control when you create an index.

**Warning**  
The JSON token is a non-validated payload. This should only be used when requests to Amazon Kendra come from a trusted server and never from a browser. 

------
#### [ Console ]

1. Choose **Create index** to start creating a new index.

1. On the **Specify index details** page, give your index a name and a description. 

1. For **IAM role**, select a role or select **Create a new role** to and specify a role name to create a new role. The IAM role will have the prefix "AmazonKendra-". 

1. Leave all of the other fields at their defaults. Choose **Next**.

1. In the **Configure user access control** page, under **Access control settings**, choose **Yes** to use tokens for access control. 

1. Under **Token configuration**, select **JSON** as the **Token type**. 

1. Specify a **User name** to use in the ACL check.

1. Specify one or more **Groups** to use in the ACL check.

1. Choose **Next**.

1. In the **Provisioning details** page, choose **Developer edition**.

1. Choose **Create** to create your index.

1. Wait for your index to be created. Amazon Kendra provisions the hardware for your index. This operation can take some time.

------
#### [ CLI ]

To create an index with the AWS CLI using a JSON input file, first create a JSON file with your desired parameters:

```
{
    "Name": "user-context",
    "Edition": "ENTERPRISE_EDITION",
    "RoleArn": "arn:aws:iam::account-id:role:/my-role",
    "UserTokenConfigurations": [
        {
            "JsonTokenTypeConfiguration": {
                "UserNameAttributeField": "user",
                "GroupAttributeField": "group"
            }
        }
    ],
    "UserContextPolicy": "USER_TOKEN"
}
```

Next, call `create-index` using the input file. For example, if the name of your JSON file is `create-index-openid.json`, you can use the following: 

```
aws kendra create-index --cli-input-json file://create-index-openid.json
```

If you are not using Open ID for AWS IAM Identity Center, you can send us the token in JSON format. If you do, you must specify which field in the JSON token contains the user name and which field contains the groups. The group field values must be a JSON string array. For example, if you are using SAML, your token would be similar to the following:

```
{
     "username" : "user1", 
     "groups": [
        "group1", 
        "group2"
     ]
}
```

The `TokenConfiguration` would specify the user name and group field names:

```
{
    "UserNameAttributeField":"username",
    "GroupAttributeField":"groups"
}
```

------
#### [ Python ]

```
response = kendra.create_index(
    Name='user-context',
    Edition='ENTERPRISE_EDITION',
    RoleArn='arn:aws:iam::account-id:role:/my-role',
    UserTokenConfigurations=[
        {
            "JwtTokenTypeConfiguration": {
                "UserNameAttributeField": "user",
                "GroupAttributeField": "group",
            }
        }
    ],
    UserContextPolicy='USER_TOKEN'
)
```

------