You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

People API中对应ContactsApp.getContactsByCustomField的等效方法是什么?

问题描述

我在旧版App Script中使用以下语法按自定义字段搜索联系人:

var contacts = ContactsApp.getContactsByCustomField('tennis', 'Favorite Sport')

目前迁移至People API后,尝试用searchContacts接口搜索自定义字段失败:

var response = People.People.searchContacts({ query: "tennis", readMask: "names,userDefined" })

请问People API中对应的等效方法是什么?

解决方案

People API的searchContacts接口仅支持对姓名、邮箱、电话号码等默认字段进行检索,不支持直接搜索自定义userDefined字段。要实现旧版getContactsByCustomField的功能,需要先获取所有联系人列表,再在本地过滤符合条件的条目,具体步骤如下:

  1. 使用People.People.listContacts接口批量获取联系人(需处理分页,避免因联系人数量过多导致请求失败)
  2. 遍历返回的联系人,筛选出userDefined字段中匹配目标键值对的条目

示例代码:

function getContactsByCustomField(fieldKey, fieldValue) {
  const matchedContacts = [];
  let pageToken = null;

  do {
    // 分页获取联系人,指定需要读取的字段
    const response = People.People.listContacts({
      readMask: "names,userDefined",
      pageToken: pageToken,
      pageSize: 100 // 单次请求最大返回数量,可根据需求调整
    });

    if (response.connections) {
      // 过滤符合自定义字段条件的联系人
      const filtered = response.connections.filter(contact => {
        // 检查联系人是否包含userDefined字段,且存在匹配的键值对
        return contact.userDefined?.some(item => 
          item.key === fieldKey && item.value === fieldValue
        );
      });
      matchedContacts.push(...filtered);
    }

    pageToken = response.nextPageToken;
  } while (pageToken); // 循环直到所有分页数据都处理完成

  return matchedContacts;
}

// 使用示例:查找"Favorite Sport"为"tennis"的联系人
const targetContacts = getContactsByCustomField("Favorite Sport", "tennis");
console.log(targetContacts);

说明

  • 这种方式需要先拉取所有联系人数据,若你的联系人数量极大(比如超过1万条),可能会有一定的性能开销,但目前People API没有提供直接检索自定义字段的接口,这是最可行的替代方案。
  • 确保在App Script中已启用People API服务(通过「编辑器」>「服务」> 添加「People API」)。

内容的提问来源于stack exchange,提问作者lito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:55:23