gpt4 book ai didi

perl - 使用Perl动态修改ElasticSearch查询

转载 作者:行者123 更新时间:2023-12-03 00:40:57 27 4
gpt4 key购买 nike

在工作中,我有一个脚本,由不在家的人制作。它用于检索节点如下所示的XML文件:

 <query maxresults='15000'>
<![CDATA[
and(
isavailable:1,
not(designation:string("test wine", mode="or")),
visibility:10,
bestprice:>0
)
]]>
</query>

我们正在为此使用Perl。目的是修改节点内包含的FAST请求,以动态添加一些参数(例如,使用“maxresults”属性限制结果)。这部分代码有效,但是我们要切换到ElasticSearch,我需要更改代码才能起作用。

问题是,我找不到用Perl修改ElasticSearch查询的可靠方法。到目前为止,我做到了:
use strict;
use warnings;
use JSON;
use Data::Dumper;
use Search::Elasticsearch;

my $json =
'{"query":
{"bool":
{"must":
[
{"term":
{"isavailable":"1"}
},
{"term":
{"visibility":"10"}
},
{"range":
{"bestprice":
{"gt":"0"}
}
}

],
"must_not":
[{"regexp":
{"designation":"[Tt]+[Ee]+[Ss]+[Tt]+"}
},
{"regexp":
{"designation":"[Ww]+[Ii]+[Ne]+[Ee]+"}
}
]
}
}
}';

my $result = decode_json($json);

但这给了我一个哈希,而不是一个对象,而尝试动态修改此哈希以添加(例如)使我头疼:
{"regexp": {"designation":"[Ff]+[Oo]+"}}

到“must_not”对象内的数组。

我尝试这样做:
my %must = (must_not => [{"regexp" => 
{"designation" => "[Ff]+[Oo]+"}
}
]);


$result{"query"} = \%must;

print keys(%{$result{query}});

但这只是用%must哈希替换了整个节点的内容,而我找不到合适的附加方法。我试图在must_not对象中包含的数组内推送哈希,但是我只会得到错误。

我对这种情况感到非常困惑,特别是因为我并不是Perl专家,所以任何帮助都值得欢迎!

谢谢!

最佳答案

它不是对象,因为Perl默认情况下不使用对象。如果需要一个对象,则需要有一个类,然后实例化它。但是decode_json无法做到这一点。它所做的只是返回一个复杂的数据结构。

要将另一个条目添加到将过滤器保存在该数据结构内部的数组ref中,您需要对其进行 push 。为此,您需要取消引用数组ref,因为push不喜欢对引用进行操作。 Perl将使用以下语法为您做正确的事情。

#    this dereferences the array ref for push
# | |
push @{ $result->{query}->{bool}->{must_not} }, { # the { starts a new hash ref
"regexp" => {
"designation" => "[Ff]+[Oo]+", # we like trailing commas in Perl
},
};

如果您有一个非常新的Perl(5.24),也可以在此处使用post-fix deref语法,这样阅读起来会更干净。
push $result->{query}->{bool}->{must_not}->@, { ... };

关于perl - 使用Perl动态修改ElasticSearch查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com