Skip to content

Commit

Permalink
fix(next/api): ES multi_match query cannot match nested field
Browse files Browse the repository at this point in the history
  • Loading branch information
sdjdd committed Apr 2, 2024
1 parent adf4d0a commit b6a452b
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions next/api/src/service/search-ticket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Client } from '@elastic/elasticsearch';
import { Queue } from 'bull';
import esb from 'elastic-builder';
import esb, { Query as ESQuery } from 'elastic-builder';
import _ from 'lodash';

import {
Expand Down Expand Up @@ -285,15 +285,23 @@ export class SearchTicketService {
filters.fields.forEach((match) => addNestedQuery('fields', match));
}
if (filters.keyword) {
const terms = this.parseTerms(filters.keyword);
terms.forEach((term) => {
const matchQuery = esb
.multiMatchQuery(['title', 'content', 'fields.value'], term.value)
.operator('and');
this.parseTerms(filters.keyword).forEach((term) => {
let normalMatchQuery: ESQuery;
let nestedMatchQuery: ESQuery;
if (term.isPhrase) {
matchQuery.type('phrase');
normalMatchQuery = esb.multiMatchQuery(['title', 'content'], term.value).type('phrase');
nestedMatchQuery = esb.nestedQuery(
esb.matchPhraseQuery('fields.value', term.value),
'fields'
);
} else {
normalMatchQuery = esb.multiMatchQuery(['title', 'content'], term.value).operator('and');
nestedMatchQuery = esb.nestedQuery(
esb.matchQuery('fields.value', term.value).operator('and'),
'fields'
);
}
boolQuery.filter(matchQuery);
boolQuery.filter(esb.boolQuery().should([normalMatchQuery, nestedMatchQuery]));
});
}

Expand All @@ -307,6 +315,9 @@ export class SearchTicketService {
.source(false)
.toJSON();

console.log('[Search Ticket]: Query:');
console.dir(body, { depth: 10 });

const res = await this.esClient.search({
index: this.indexName,
body,
Expand Down

0 comments on commit b6a452b

Please sign in to comment.