使用elasticsearch和nestjs添加索引分析器

mutmk8jj  于 2023-08-03  发布在  ElasticSearch
关注(0)|答案(2)|浏览(135)

我用的是@nestjs/elasticsearch,想用Bulgarian analyzer,因为搜索太简单了

const result = await this.elasticsearchService.search<Question>({
      index: this.index,
      query: {
        multi_match: {
          query: text,
          fields: ['body', 'tags.name'],
          analyzer: 'bulgarian',
        },
      },
    });

字符串
但没有类似的索引可用,这是当前代码

this.elasticsearchService.index<Question>({
      index: this.index,
      id: question.id.toString(),
      document: question,
    });


我从这里读到https://stackoverflow.com/a/33219447/2748984应该是通过Map完成的,但是index方法也不需要Map,这里是index接口

export interface IndexRequest<TDocument = unknown> extends RequestBase {
    id?: Id;
    index: IndexName;
    if_primary_term?: long;
    if_seq_no?: SequenceNumber;
    op_type?: OpType;
    pipeline?: string;
    refresh?: Refresh;
    routing?: Routing;
    timeout?: Duration;
    version?: VersionNumber;
    version_type?: VersionType;
    wait_for_active_shards?: WaitForActiveShards;
    require_alias?: boolean;
    document?: TDocument;
}


我没有看到任何与Map或分析器相关的选项

bvjxkvbb

bvjxkvbb1#

必须有一个this.elasticsearchService.create(...)函数,它允许您使用question you've linked to中的特定Map创建索引,类似于以下内容:

this.elasticsearchService.indices.create<Question>({
  index: this.index,
  mapping: ...,
});

字符串

bq9c1y66

bq9c1y662#

这是真正起作用的代码

async indexQuestion(question: Question): Promise<IndexResponse> {
    if (
      !(await this.elasticsearchService.indices.exists({ index: this.index }))
    ) {
      await this.elasticsearchService.indices.create({
        index: this.index,
        mappings: {
          properties: {
            body: {
              type: 'text',
              analyzer: 'bulgarian',
              fields: {
                keyword: {
                  type: 'keyword',
                  ignore_above: 256,
                },
              },
            },
            'tags.name': {
              type: 'text',
              analyzer: 'bulgarian',
              fields: {
                keyword: {
                  type: 'keyword',
                  ignore_above: 256,
                },
              },
            },
          },
        },
      });
    }

    return this.elasticsearchService.index<Question>({
      index: this.index,
      id: question.id.toString(),
      document: question,
    });
  }

字符串

相关问题