Warm tip: This article is reproduced from serverfault.com, please click

How to delete all fields created in MarkLogic

发布于 2020-12-10 13:49:02

I have a requirement whereby existing fields needs to be deleted. I found perfect script for deletion of field-range indexes but not for fields. So, I wrote this script which works fine but I need to pass each field-name one by one :

xquery version "1.0-ml";

  import module namespace admin = "http://marklogic.com/xdmp/admin"
          at "/MarkLogic/admin.xqy";

  let $config := admin:get-configuration()
  let $dbid := xdmp:database("testDB")
  let $fields := admin:database-get-fields($config,$dbid)
  for $each in $fields
  let $config := admin:database-delete-field($config, $dbid,$each/*:field-name/fn:string())
  return admin:save-configuration($config) 

Does anyone else has a better solution for this? Whereby we can directly pass fields and it's done.

Questioner
Shabana
Viewed
0
grtjn 2020-12-10 23:03:23

The function admin:database-delete-field() accepts multiple field names, so you can skip the FLWOR:

xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
      at "/MarkLogic/admin.xqy";

let $config := admin:get-configuration()
let $dbid := xdmp:database("testDB")
let $fields := admin:database-get-fields($config,$dbid)
let $config := admin:database-delete-field($config, $dbid, $fields/*:field-name)
return admin:save-configuration($config)

That said, if you find yourself in a position where you cannot avoid a FLWOR, use xdmp:set to iteratively update $config, and finish with a single save-config. Your code was executing that for each FLWOR iteration. Something like this should work too:

xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
      at "/MarkLogic/admin.xqy";

let $config := admin:get-configuration()
let $dbid := xdmp:database("testDB")
let $fields := admin:database-get-fields($config,$dbid)
let $_ :=
    for $each in $fields
    return xdmp:set($config, admin:database-delete-field($config, $dbid, $each/*:field-name))
return admin:save-configuration($config)

HTH!