How do I get output for a XQuery in MarkLogic in a one line output? - xquery

Will elaborate - when I execute the following command :
let $value := xdmp:forest-status(
xdmp:forest-open-replica(
xdmp:database-forests(xdmp:database("Documents"))))
return $value
Above query returns a lot of information about the database "Documents" forest, like - forest-id, host-id, etc.
I only require that it should return only the "state" of my forest. How do I do that?

Use XPath to select what you want to return.
let $value := xdmp:forest-status(
xdmp:forest-open-replica(
xdmp:database-forests(xdmp:database("Documents"))))
return $value/*:state/text()
Also, no need for a FLWOR you could make it a one-liner:
xdmp:forest-status(
xdmp:forest-open-replica(
xdmp:database-forests(xdmp:database("Documents"))))/*:state/text()
Or you may find that using the arrow operator makes things easier to read instead of nested function calls and tons of parenthesis wrapping them:
(xdmp:database("Documents")
=> xdmp:database-forests()
=> xdmp:forest-open-replica()
=> xdmp:forest-status()
)/*:state/text()
The XML elements in the response are in the http://marklogic.com/xdmp/status/forest namespace. So, you would either need to declare the namespace (i.e. declare namespace f = "http://marklogic.com/xdmp/status/forest";) and use the prefix in your XPath (i.e. f:state), or just use the wildcard as I have done *:state

Related

Oracle named parameters

How can I use keywords with Oracle named parameters syntax ? The following gives me 'ORA-00936: missing expression' because of the 'number'-argument:
select b.g3e_fid
, a.g3e_fid
, sdo_nn_distance( 1)
from acn a, b$gc_fitface_s b
where mdsys.sdo_nn ( geometry1 => a.g3e_geometry, geometry2 => b.g3e_geometry, param => 'sdo_num_res=1', number=>1) = 'TRUE' and b.g3e_fid = 57798799;
If I run it without named parameters it is fine.
thanks, Steef
Although you can get around the reserved word issue in your call by enclosing the name in double quotes as #AvrajitRoy suggested, i.e. ... "NUMBER"=>1) = 'TRUE'..., you aren't actually achieving much. Oracle is letting you refer to the parameters by name but it isn't doing anything with that information.
MDSYS.SDO_NN is a spatial operator, not a direct call to a function. There is a function backing it up - you can see from the schema scripts for MDSYS that it's actually calling prtv_idx.nn - but the names of the formal parameters of that function are not relevant. With some digging you can see those are actually called geom, geom2, mask etc., and there isn't one called number (and you can't have a formal parameter called number, even quoting it, as far as I can tell).
The formal parameters to the operator are not named, and are effectively passed through positionally. You can't skip an argument by naming the others, as you can with a function/procedure with arguments that have default values.
So that means you can call the parameters anything you want in your call; changing the names of the first three parameters in your call to something random won't stop it working.
It also means naming them in the call is a bit pointless, but if you're just trying to document the call then you can use some other meaningful name rather than 'number' if you don't want to quote it.
Hello as mentined in you question . There are two ways in which u can eliminate this RESERVED keyword ISSUE.
1) Use "" to use any RESERVED key word for calling. But remember this is not a good coding practice.
Eg >
SELECT b.g3e_fid ,
a.g3e_fid ,
sdo_nn_distance( 1)
FROM acn a,
b$gc_fitface_s b
WHERE mdsys.sdo_nn
( geometry1 => a.g3e_geometry,
geometry2 => b.g3e_geometry,
"param" => 'sdo_num_res=1',
"NUMBER"=>1) = 'TRUE'
AND b.g3e_fid = 57798799;
2) Secondly you can just call the function without using "=>" as shown below
Eg >
SELECT b.g3e_fid ,
a.g3e_fid ,
sdo_nn_distance( 1)
FROM acn a,
b$gc_fitface_s b
WHERE mdsys.sdo_nn
( a.g3e_geometry,
b.g3e_geometry,
'sdo_num_res=1',
1) = 'TRUE'
AND b.g3e_fid = 57798799;

How to set the value of one field to another filed in using XQuery

Very new to XQuery and MarkLogic, what is the XQuery version of the following statement?
update all_the_records
set B_field = A_field
where B_field is null and A_field is not null
Something like this might get you started. But remember that you're working with trees, not tables. Things are generally more complicated because of that extra dimension.
for $doc in collection()/doc[not(b)][a]
let $a as element() := $doc/a
return xdmp:node-insert-child($doc, element b { $a/#*, $a/node() })

idl: pass keyword dynamically to isa function to test structure read by read_csv

I am using IDL 8.4. I want to use isa() function to determine input type read by read_csv(). I want to use /number, /integer, /float and /string as some field I want to make sure float, other to be integer and other I don't care. I can do like this, but it is not very readable to human eye.
str = read_csv(filename, header=inheader)
; TODO check header
if not isa(str.(0), /integer) then stop
if not isa(str.(1), /number) then stop
if not isa(str.(2), /float) then stop
I am hoping I can do something like
expected_header = ['id', 'x', 'val']
expected_type = ['/integer', '/number', '/float']
str = read_csv(filename, header=inheader)
if not array_equal(strlowcase(inheader), expected_header) then stop
for i=0l,n_elements(expected_type) do
if not isa(str.(i), expected_type[i]) then stop
endfor
the above doesn't work, as '/integer' is taken literally and I guess isa() is looking for named structure. How can you do something similar?
Ideally I want to pick expected type based on header read from file, so that script still works as long as header specifies expected field.
EDIT:
my tentative solution is to write a wrapper for ISA(). Not very pretty, but does what I wanted... if there is cleaner solution , please let me know.
Also, read_csv is defined to return only one of long, long64, double and string, so I could write function to test with this limitation. but I just wanted to make it to work in general so that I can reuse them for other similar cases.
function isa_generic,var,typ
; calls isa() http://www.exelisvis.com/docs/ISA.html with keyword
; if 'n', test /number
; if 'i', test /integer
; if 'f', test /float
; if 's', test /string
if typ eq 'n' then return, isa(var, /number)
if typ eq 'i' then then return, isa(var, /integer)
if typ eq 'f' then then return, isa(var, /float)
if typ eq 's' then then return, isa(var, /string)
print, 'unexpected typename: ', typ
stop
end
IDL has some limited reflection abilities, which will do exactly what you want:
expected_types = ['integer', 'number', 'float']
expected_header = ['id', 'x', 'val']
str = read_csv(filename, header=inheader)
if ~array_equal(strlowcase(inheader), expected_header) then stop
foreach type, expected_types, index do begin
if ~isa(str.(index), _extra=create_struct(type, 1)) then stop
endforeach
It's debatable if this is really "easier to read" in your case, since there are only three cases to test. If there were 500 cases, it would be a lot cleaner than writing 500 slightly different lines.
This snipped used some rather esoteric IDL features, so let me explain what's happening a bit:
expected_types is just a list of (string) keyword names in the order they should be used.
The foreach part iterates over expected_types, putting the keyword string into the type variable and the iteration count into index.
This is equivalent to using for index = 0, n_elements(expected_types) - 1 do and then using expected_types[index] instead of type, but the foreach loop is easier to read IMHO. Reference here.
_extra is a special keyword that can pass a structure as if it were a set of keywords. Each of the structure's tags is interpreted as a keyword. Reference here.
The create_struct function takes one or more pairs of (string) tag names and (any type) values, then returns a structure with those tag names and values. Reference here.
Finally, I replaced not (bitwise not) with ~ (logical not). This step, like foreach vs for, is not necessary in this instance, but can avoid headache when debugging some types of code, where the distinction matters.
--
Reflective abilities like these can do an awful lot, and come in super handy. They're work-horses in other languages, but IDL programmers don't seem to use them as much. Here's a quick list of common reflective features I use in IDL, with links to the documentation for each:
create_struct - Create a structure from (string) tag names and values.
n_tags - Get the number of tags in a structure.
_extra, _strict_extra, and _ref_extra - Pass keywords by structure or reference.
call_function - Call a function by its (string) name.
call_procedure - Call a procedure by its (string) name.
call_method - Call a method (of an object) by its (string) name.
execute - Run complete IDL commands stored in a string.
Note: Be very careful using the execute function. It will blindly execute any IDL statement you (or a user, file, web form, etc.) feed it. Never ever feed untrusted or web user input to the IDL execute function.
You can't access the keywords quite like that, but there is a typename parameter to ISA that might be useful. This is untested, but should work:
expected_header = ['id', 'x', 'val']
expected_type = ['int', 'long', 'float']
str = read_cv(filename, header=inheader)
if not array_equal(strlowcase(inheader), expected_header) then stop
for i = 0L, n_elemented(expected_type) - 1L do begin
if not isa(str.(i), expected_type[i]) then stop
endfor

xquery beginner- how to use an if-then-else within a FLWOR statement

I want to extract some content from a web page's XML equivalent, using XQuery.
Here, I want to use if-then-else -- if a specific condition is met, then one value is returned by the xquery expression, otherwise a different value is returned.
This is the expression I have with me--
I am working to extract some content from a web page.
Given below is the Xquery code I am using-- I am using a XQuery library to parse through XML which is obtained by transforming a HTML web page into XML...after that I am extracting some specific content from that XML page...
declare variable $doc as node() external;
let $select_block := $doc//div[#class="randomclass" and contains(.,'MatchingText')]
for $select_link in $select_block/a
for $select_link_url in $select_link/#href
where contains($assignee_link_url,'inassignee')
return data($select_link)
Now how do I use if-then-else within this expression?
I tried to add an if-then immediately after 'return' keyword but I am getting error...
Basically, if some content is found for $select_block above, then data($select_link) should be returned, otherwise the static text 'Missing Value' should be returned.
What is the correct way of using if-then-else with the above xquery expression?
If I understand what you are trying to achieve correctly, then the following should work:
declare variable $doc as node() external;
let $select_block := $doc//div[#class="randomclass" and contains(.,'MatchingText')]
return
if ($select_block) then
for $select_link in $select_block/a
for $select_link_url in $select_link/#href
where contains($select_link_url,'inassignee')
return data($select_link)
else 'Missing Value'
You could simplify things a little bit and eliminate the nested for loops with predicate filters selecting the anchor elements:
declare variable $doc as node() external;
let $select_block := $doc//div[#class="randomclass" and contains(.,'MatchingText')]
return
if ($select_block) then
for $select_link in $select_block/a[#href[contains(., 'inassignee')]]
return data($select_link)
else 'Missing Value'

To remove the node but keep the value inside intact through XQuery

I have a content.xml modelled as below
<root>
<childnode>
Some text here
</childnode>
</root>
I am trying to remove the <childnode> and update the content.xml with only the value of it
so the output looks like
<root>
Some Text here
</root>
I wrote a function to perform this but anytime I run it it gives me error as "unexpected token: modify". I was thinking of a way to accomplish this without using functx functions.
xquery version "1.0";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace file="http://exist-db.org/xquery/file";
declare namespace system="http://exist-db.org/xquery/system";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace response="http://exist-db.org/xquery/response";
declare function local:contentUpdate() {
let $root := collection('/lib/repository/content')//root/childNode
let $rmChild := for $child in $root
modify
(
return rename node $child as ''
)
};
local:updateTitle()
Thanks in advance
There are multiple problems with your query:
Updating functions must be declared as updating.
You're calling another function than you defined (probably you didn't notice as there still have been syntax errors).
Rename node expects some element (or processing instruction, attribute) as target, the empty string is not allowed.
At least BaseX doesn't allow updating statements when defining code as XQuery 1.0. Maybe exist doesn't care about this, try adding it if you need to know.
You do not want to rename, but replace all <childnode />s with its contents, use replace node.
This code fixes all these problems:
declare updating function local:contentUpdate() {
let $root := collection('/lib/repository/content')
return
for $i in $root//childnode
return
replace node $i with $i/data()
};
local:contentUpdate()
eXist-db's XQuery Update syntax is documented at http://exist-db.org/exist/update_ext.xml. Note that this syntax predates the release of the XQuery Update Facility 1.0, so the syntax is different and remains unique to eXist-db.
The way to do what you want in eXist-db is as follows:
xquery version "1.0";
declare function local:contentUpdate() {
let $root := doc('/db/lib/repository/content/content.xml')/root
return
update value $root with $root/string()
};
local:contentUpdate()
The primary changes, compared to your original code, are:
Inserted the eXist-db syntax for your update
Prepended '/db' to your collection name, as /db is the root of the database in eXist-db; replaced the collection() call with a doc() call, since you stated you were operating on a single file, content.xml
Changed //root to /root, since "root" is the root element, so the // (descendant-or-self) axis is extraneous
Replaced updateTitle() with the actual name of the function, contentUpdate
Removed the extraneous namespace declarations
For more on why I used $root/string(), see http://community.marklogic.com/blog/text-is-a-code-smell.

Resources