JavaScript客户端 #

安装 #

npm安装 #

bash
npm install algoliasearch

CDN引入 #

html
<!-- 完整版 -->
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script>

<!-- 轻量版(仅搜索功能) -->
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script>

初始化 #

基本初始化 #

javascript
import algoliasearch from 'algoliasearch';

const client = algoliasearch('APP_ID', 'SEARCH_KEY');
const index = client.initIndex('products');

初始化选项 #

javascript
const client = algoliasearch('APP_ID', 'SEARCH_KEY', {
  hosts: {
    read: ['app-id-dsn.algolia.net'],
    write: ['app-id.algolia.net']
  },
  requestOptions: {
    headers: {
      'X-Custom-Header': 'value'
    }
  }
});

搜索操作 #

基本搜索 #

javascript
// Promise方式
index.search('iphone')
  .then(({ hits }) => {
    console.log(hits);
  })
  .catch(err => {
    console.error(err);
  });

// async/await方式
async function search(query) {
  try {
    const { hits, nbHits, page } = await index.search(query);
    return hits;
  } catch (err) {
    console.error('Search failed:', err);
    return [];
  }
}

带参数搜索 #

javascript
const results = await index.search('iphone', {
  hitsPerPage: 20,
  page: 0,
  filters: 'brand:Apple',
  facets: ['brand', 'category'],
  attributesToHighlight: ['name', 'description']
});

搜索结果处理 #

javascript
function processResults(results) {
  return {
    items: results.hits.map(hit => ({
      id: hit.objectID,
      name: hit._highlightResult.name.value,
      price: hit.price,
      image: hit.imageUrl
    })),
    total: results.nbHits,
    page: results.page,
    totalPages: results.nbPages,
    processingTime: results.processingTimeMS
  };
}

索引操作 #

添加记录 #

javascript
// 添加单条记录
await index.saveObject({
  objectID: 'prod-001',
  name: 'iPhone 15 Pro',
  price: 999
});

// 批量添加
await index.saveObjects([
  { objectID: 'prod-001', name: 'Product 1' },
  { objectID: 'prod-002', name: 'Product 2' }
]);

更新记录 #

javascript
// 完全替换
await index.saveObject({
  objectID: 'prod-001',
  name: 'Updated Name',
  price: 899
});

// 部分更新
await index.partialUpdateObject({
  objectID: 'prod-001',
  price: 899
});

删除记录 #

javascript
// 删除单条
await index.deleteObject('prod-001');

// 批量删除
await index.deleteObjects(['prod-001', 'prod-002']);

// 按条件删除
await index.deleteBy({
  filters: 'stock:0'
});

// 清空索引
await index.clearObjects();

批量操作 #

javascript
await index.batch({
  requests: [
    { action: 'addObject', body: { name: 'Product 1' } },
    { action: 'updateObject', body: { objectID: '1', name: 'Updated' } },
    { action: 'deleteObject', objectID: '2' }
  ]
});

索引设置 #

获取设置 #

javascript
const settings = await index.getSettings();
console.log(settings);

更新设置 #

javascript
await index.setSettings({
  searchableAttributes: ['name', 'description', 'brand'],
  attributesForFaceting: ['brand', 'category'],
  customRanking: ['desc(rating)'],
  hitsPerPage: 20
});

多索引搜索 #

javascript
const queries = [
  { indexName: 'products', query: 'iphone', params: { hitsPerPage: 5 } },
  { indexName: 'articles', query: 'iphone', params: { hitsPerPage: 3 } }
];

const { results } = await client.multipleQueries(queries);

分面搜索 #

获取分面值 #

javascript
const results = await index.search('', {
  facets: ['brand', 'category']
});

console.log(results.facets);

搜索分面值 #

javascript
const { facetHits } = await index.searchForFacetValues('brand', 'Ap');
console.log(facetHits);

同义词操作 #

javascript
// 添加同义词
await index.saveSynonym({
  objectID: 'syn-1',
  type: 'synonym',
  synonyms: ['手机', '电话', '移动电话']
});

// 获取同义词
const synonym = await index.getSynonym('syn-1');

// 删除同义词
await index.deleteSynonym('syn-1');

规则操作 #

javascript
// 添加规则
await index.saveRule({
  objectID: 'rule-1',
  condition: { pattern: 'sale', anchoring: 'contains' },
  consequence: {
    params: { filters: 'onSale:true' }
  }
});

// 获取规则
const rule = await index.getRule('rule-1');

// 删除规则
await index.deleteRule('rule-1');

错误处理 #

javascript
try {
  const results = await index.search('iphone');
} catch (err) {
  if (err.status === 403) {
    console.error('API Key权限不足');
  } else if (err.status === 404) {
    console.error('索引不存在');
  } else {
    console.error('搜索失败:', err.message);
  }
}

完整示例 #

javascript
import algoliasearch from 'algoliasearch';

class AlgoliaService {
  constructor(appId, apiKey, indexName) {
    this.client = algoliasearch(appId, apiKey);
    this.index = this.client.initIndex(indexName);
  }
  
  async search(query, options = {}) {
    const defaultOptions = {
      hitsPerPage: 20,
      page: 0,
      attributesToHighlight: ['name', 'description']
    };
    
    return await this.index.search(query, { ...defaultOptions, ...options });
  }
  
  async addObjects(objects) {
    return await this.index.saveObjects(objects);
  }
  
  async updateObject(objectID, updates) {
    return await this.index.partialUpdateObject({
      objectID,
      ...updates
    });
  }
  
  async deleteObject(objectID) {
    return await this.index.deleteObject(objectID);
  }
  
  async getFacets(facets) {
    const results = await this.index.search('', { facets });
    return results.facets;
  }
}

// 使用
const service = new AlgoliaService('APP_ID', 'SEARCH_KEY', 'products');
const results = await service.search('iphone');

总结 #

JavaScript客户端要点:

要点 说明
初始化 algoliasearch(APP_ID, API_KEY)
搜索 index.search(query, params)
索引 saveObjects, deleteObjects
设置 setSettings, getSettings
分面 facets, searchForFacetValues

接下来,让我们学习 React集成

最后更新:2026-03-28