我正在尝试使用" 匹配"中的一些元素来丰富我的搜索结果。文档,使用查询选项" extract-document-data "喜欢
<options xmlns="http://marklogic.com/appservices/search">
<extract-document-data selected="include">
<extract-path>/language-version/language-version-canonical-model/title</extract-path>
<extract-path>/language-version/language-version-canonical-model/language</extract-path>
</extract-document-data>
(...)
</options>
当我运行搜索并询问Json输出时(使用标题Accept:application/json
)我得到 json 和&#34; strinxml &#34;结果:
{
"snippet-format": "snippet",
"total": 564,
"start": 1,
"page-length": 10,
"selected": "include",
"results": [
{
"index": 1,
"uri": "ENV/CHEM/NANO(2015)22/ANN5/2",
"path": "fn:doc(\"ENV/CHEM/NANO(2015)22/ANN5/2\")",
(...)
"matches": [
{
"path": "fn:doc(\"ENV/CHEM/NANO(2015)22/ANN5/2\")/ns2:language-version/ns2:language-version-raw-data/*:document/*:page[22]",
(...)
}
],
"extracted": {
"kind": "element",
"content": [
"<language>En</language>",
"<title>ZINC OXIDE DOSSIERANNEX 5</title>",
"<reference>ENV/CHEM/NANO(2015)22/ANN5</reference>",
"<classification>2</classification>",
"<modificationDate>2015-04-16T00:00:00.000+02:00</modificationDate>",
"<subject label_en=\"media\" >media</subject>",
"<subject label_en=\"fish\" ">fish</subject>",
]
}
},
问题在于&#34; 提取&#34;部分,正如您所看到的,看起来 xml 元素已被简单地复制为字符串,当我真的希望它们转换为 json 时。
有人对这个问题有所了解吗?
答案 0 :(得分:6)
MarkLogic不会转换内容。因此,当要求JSON格式的搜索响应时,XML将保持XML。由于您无法在JSON中真正嵌入XML,因此将其序列化为字符串。
您可以尝试对搜索结果应用REST转换,并使用类似json:transform-to-json(可能使用自定义配置)的内容来动态转换。比如像服务器端JavaScript转换这样的东西:
/* jshint node:true,esnext:true */
/* global xdmp */
var json = require('/MarkLogic/json/json.xqy');
var config = json.config('custom');
function toJson(context, params, content) {
'use strict';
var response = content.toObject();
if (response.results) {
response.results.map(function(result) {
if (result.extracted && result.extracted.content) {
result.extracted.content.map(function(content, index) {
if (content.match(/^</) && !content.match(/^<!/)) {
result.extracted.content[index] = json.transformToJson(xdmp.unquote(content), config);
}
});
}
});
}
return response;
}
exports.transform = toJson;
当然,您也可以转换客户端。
HTH!
答案 1 :(得分:1)
如果您使用的是Java Client API,则可以使用每个结果的正确句柄来阅读提取的项目(请参阅ExtractedResult和ExtractedItem):
SearchHandle results = queryManager.search(query, new SearchHandle());
for (MatchDocumentSummary summary : results.getMatchResults()) {
ExtractedResult extracted = summary.getExtracted();
// here we check to see if this result is XML format, and if so
// we use org.w3c.dom.Document
if ( Format.XML == summary.getFormat() ) {
for (ExtractedItem item : extracted) {
Document extractItem = item.getAs(new DOMHandle()).get();
...
}
// or if the result is JSON we could choose a different handle
} else if ( Format.JSON == summary.getFormat() ) {
for (ExtractedItem item : extracted) {
JsonNode extractItem = item.getAs(JsonNode.class);
...
}
}
}