首页 > 解决方案 > 如何通过 elasticsearch 将对象转换为 Json 查询

问题描述

我正在开发基于 Angular7 和 elasticsearchJS 的搜索应用程序。在我的数据服务中,我从用户输入创建了 elasticsearch json 正文查询。它适用于 this.query 的简单字符串查询。它不适用于 this.selectedTopics (我的复选框)中的复杂数组。输出在 JSON 中被销毁(参见图片)

在此处输入图像描述

在我的查询中,我在我的 console.log 中变成了反斜杠(见图)

console.log(this.selectedTopics);

  // Output of selectedTopics is this:
  //  ["Lindenholz", "Sandstein"]

  this.selectedTopics.forEach( (item) => {
      this.termarray.push('{ "term": {"79_material":"' + item + '"}}');
  });

  console.log(this.termarray.join(', '));

    // Output of termarray is this:
    //
    //  [
    //      { "term": {"79_material":"Sandstein"}},
    //      { "term": {"79_material":"Lindenholz"}}
    //  ]
    // looks fine in console. But if i send the termarray to the json body it looks wrong with the backslashes.

  this.body = {
    // 'size': this.size.value, // document anzahl
    'size': '100',
    'from': '0', // page
    'query': {
      'filtered': {
        'query' : {
            'multi_match': {
                'query': this.query,
                'type': 'phrase_prefix',
                // 'fields': ['79_material', '79_technik'] // Fulltext or Category
                'fields': this.selectedCategory
            }
        },
        'filter': {
            'bool': {
                'must': [
                  this.termarray.join(', ')
                  // {'term' : { '79_material': 'holz' }},
                  // {'term' : { '79_material': 'lindenholz' }}
                ]
            }
        }
    }
    },
    // Faceten Auswahl hier und in der Searchlist. Auf content und keyword achten.
    'facets' : {
      '79_material' : {
        'terms' : {'field' : '79_material.keyword'}
     },
      '79_technik' : {
        'terms' : {'field' : '79_technik.keyword'}
    },
      '79_kuenstler' : {
        'terms' : {'field' : '79_kuenstler.content'} // neue Indexierung mit Keyword
    },
    '79_verortung' : {
      'terms' : {'field' : '79_verortung.content'} // neue Indexierung mit Keyword
  },
  },
    'sort' : [
      { '79_material' : {'order' : 'asc'}},
      '_score'
  ]
  };

在此处输入图像描述

结果必须是这样的:

[
{'term' : { '79_material': 'holz' }},
{'term' : { '79_material': 'lindenholz' }}
]

标签: jsonangulartypescriptelasticsearch

解决方案


你试过这个吗?

this.termarray.push({ term: { '79_material': item }});

(或者:

this.termarray.push({ 'term': { '79_material': item }});
this.termarray.push({ 'term': { "79_material": item }});
this.termarray.push({ "term": { "79_material": item }});

)

更新

描述不清楚如何termarray处理,但如果您只是将项目直接添加到body

let termarray = this.body.query.filter.bool.must;
this.selectedTopics.forEach( (item) => {
    termarray.push({ term: { '79_material': item }});
});

更新 2

这是应用 UPDATE 后 Chrome 的屏幕截图:

截屏

请注意,当您应用时JSON.stringify(body),您会得到预期的输出,即没有反斜杠。


推荐阅读