我需要将下面的对象转换为另一个对象,以使其与Elasticsearch DSL兼容。我尝试了各种方法,但似乎没有一种方法可以返回准确的结果。 我的主要问题是将具有公共键的对象转换为数组。这是我的数据:
{
"aggs": {
"country_groups": {
"terms": {
"field": "country.keyword",
"size": 30000
},
"aggs": {
"max_price_and_id": {
"top_hits": {
"size": 1,
"sort": {
"video_count": "desc"
},
"_source": ["channel_id", "video_count"]
}
}
}
}
}
}
我需要将其转换为以下格式:
[
{
"must":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}
}
},
{
"should":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}
}
},
{
"should":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}
}
}
]
答案 0 :(得分:0)
我没有关于您的问题的太多信息,但是此代码段适用于您的数据集。 ìnputJSON
是包含您的数据的JSON文件。
var resultJSON = {}
resultJSON["query"]={}
resultJSON["query"]["bool"] = {}
resultJSON["query"]["bool"]["should"] = []
resultJSON["query"]["bool"]["must"] = {}
resultJSON["query"]["bool"]["minimum_should_match"] = 1
var source = inputJSON
source.forEach(currentElement =>{
if(currentElement["must"]!=undefined){
resultJSON["query"]["bool"]["must"] = currentElement["must"]
}
if(currentElement["should"]!=undefined){
resultJSON["query"]["bool"]["should"].push(currentElement["should"])
}
})
返回:
{
"query": {
"bool": {
"should": [
{
"match": {
"customer_name": {
"query": "",
"operator": "and"
}
}
},
{
"match": {
"customer_name": {
"query": "",
"operator": "and"
}
}
}
],
"must": {
"match": {
"customer_name": {
"query": "",
"operator": "and"
}
}
},
"minimum_should_match": 1
}
}
}
答案 1 :(得分:0)
const obj = [
{
"must":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}enter code here
},
},
{
"should":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}
}
},
{
"should":{
"match":{
"customer_name":{
"query":"",
"operator":"and"
}
}
}
}
]
let resultTemplate = {
query: {
bool: {
must: {},
should: [],
minimum_should_match: 1,
},
},
};
const converter = (source) => {
source.forEach((item) => {
let iKeys = Object.keys(item);
iKeys.forEach((key) => {
if (key === 'must') {
resultTemplate.query.bool[key] = item[key];
} else {
resultTemplate.query.bool[key].push(item[key]);
}
});
});
};
converter(obj);
console.log(resultTemplate);