

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 以面向為基礎的索引
<a name="indexing_search_facet"></a>

透過以面向為基礎的索引和搜尋，您可以只搜尋部分的目錄，藉此最佳化您的目錄搜尋。若要執行此作業，您可以使用結構描述 *面向*。例如，與其搜尋目錄中的所有使用者物件，您可以改為搜尋只含有員工面向的使用者物件。此效率有助於降低查詢的延遲時間與所擷取的資料量。

透過以面向為基礎的索引，您可以使用 Cloud Directory 索引 API 操作來建立索引，並將之連接到物件的面向。您也可以列出索引結果，然後根據特定面向來篩選這些結果。由於這會將搜尋範圍縮小為只包含特定面向類型的物件，因此可有效地降低查詢次數與資料量。

用於 `“facets”` 與 `[CreateIndex](https://docs.aws.amazon.com/clouddirectory/latest/APIReference/API_CreateIndex.html)` API 呼叫的 `[ListIndex](https://docs.aws.amazon.com/clouddirectory/latest/APIReference/API_ListIndex.html)` 屬性會呈現套用至物件的面向集合。此屬性僅適用於 `CreateIndex` 和 `ListIndex` API 呼叫。如下列範本程式碼所示，結構描述 ARN 使用目錄的區域、擁有者帳戶和目錄 ID 來參考 Cloud Directory 結構描述。此服務提供的結構描述不會出現在清單中。

```
String cloudDirectorySchemaArn = String.format(“arn:aws:clouddirectory:%s:%s:directory/%s/schema/CloudDirectory/1.0", region, ownerAccount, directoryId);
```

例如，下列範本程式碼會針對您的 AWS 帳戶和目錄建立特定的以面向為基礎的索引，您可以在其中列舉使用面向 `SalesDepartmentFacet` 建立的所有物件。

**注意**  
請務必在參數中使用 “facets” 值，如下所示。範本程式碼中所示的「facets」執行個體，是指由 Cloud Directory 服務提供及控制的值。您可以使用這些值來編製索引，但只能進行唯讀存取。

```
// Create a facet-based index
String cloudDirectorySchemaArn = String.format(“arn:aws:clouddirectory:%s:%s:directory/%s/schema/CloudDirectory/1.0",
    region, ownerAccount, directoryId);

facetIndexResult = clouddirectoryClient.createIndex(new CreateIndexRequest() 
  .withDirectoryArn(directoryArn) 
  .withOrderedIndexedAttributeList(List(new AttributeKey()     
        .withSchemaArn(cloudDirectorySchemaArn)     
        .withFacetName("facets")     
        .withName("facets"))) 
        .withIsUnique(false) 
        .withParentReference("/") 
        .withLinkName("MyFirstFacetIndex"))
facetIndex = facetIndexResult.getObjectIdentifier()

// Attach objects to the facet-based index
clouddirectoryClient.attachToIndex(new AttachToIndexRequest().withDirectoryArn(directoryArn)
  .withIndexReference(facetIndex).withTargetReference(userObj))

// List all objects
val listResults = clouddirectoryClient.listIndex(new ListIndexRequest()
  .withDirectoryArn(directoryArn)
  .withIndexReference(facetIndex)
  .getIndexAttachments()

// List the index results filtering for a certain facet
val filteredResults = clouddirectoryClient.listIndex(new ListIndexRequest()
  .withDirectoryArn(directoryArn)
  .withIndexReference(facetIndex)
  .withRangesOnIndexedValues(new ObjectAttributeRange()
    .withAttributeKey(new AttributeKey()
      .withFacetName("facets")
      .withName("facets")
      .withSchemaArn(cloudDirectorySchemaArn))
    .withRange(new TypedAttributeValueRange()
      .withStartMode(RangeMode.INCLUSIVE)
      .withStartValue("MySchema/1.0/SalesDepartmentFacet")
      .withEndMode(RangeMode.INCLUSIVE)
      .withEndValue("MySchema/1.0/SalesDepartmentFacet")
    )))
```