Pivot XML into SQL Columns & values - sql-server

I have an XML file in the following format. Not every field name will have a value. Each field except for the id field will be varchar(40).
<index>
<doc id="0">
<field name="MFG">
<val>ACME</val>
</field>
<field name="InternalCode">
<val />
</field>
<field name="partnumber">
<val>012345-00</val>
</field>
<field name="partdescription">
<val>PIN</val>
</field>
</doc>
<doc id="1">
<field name="MFG">
<val />
</field>
<field name="InternalCode">
<val>ABCDE</val>
</field>
<field name="partnumber">
<val>919-555-7Z</val>
</field>
<field name="partdescription">
<val>WASHER</val>
</field>
</doc>
<doc id="2">
<field name="MFG">
<val>YOUR COMPANY</val>
</field>
<field name="InternalCode">
<val />
</field>
<field name="partnumber">
<val>131415</val>
</field>
<field name="partdescription">
<val>BOLT</val>
</field>
</doc>
</index>
What I would like to do is to read the XML & populate a table in SQL in the following manner.
In other words, after the rowid, pivot the rest of the attributes as columns and their values as the column value. I'm using the following code that will list the rowid, attribute & their values as rows.
SELECT XMLAttribute.rowid, XMLAttribute.name, XMLAttribute.val
FROM OPENXML (#hdoc, 'index/doc/field', 2 )
WITH (rowid int '../#id',
name VARCHAR(128) '#name',
val varchar(128) 'val'
) AS XMLAttribute
Can this (pivot after the rowid) be done? If so, how?

You can better do this with XPath/XQuery than with OPENXML. Check out documentation on XML.nodes() and XML.value(). Check out some XPath guide online, this is a good one.
DECLARE #i XML=
'<index>
<doc id="0"><field name="MFG"><val>ACME</val></field><field name="InternalCode"><val /></field><field name="partnumber"><val>012345-00</val></field><field name="partdescription"><val>PIN</val></field></doc>
<doc id="1"><field name="MFG"><val /></field><field name="InternalCode"><val>ABCDE</val></field><field name="partnumber"><val>919-555-7Z</val></field><field name="partdescription"><val>WASHER</val></field></doc>
<doc id="2"><field name="MFG"><val>YOUR COMPANY</val></field><field name="InternalCode"><val /></field><field name="partnumber"><val>131415</val></field><field name="partdescription"><val>BOLT</val></field></doc>
</index>';
SELECT
rowid=n.v.value('#id','VARCHAR(40)'),
MFG=n.v.value('(field[#name="MFG"]/val)[1]','VARCHAR(40)'),
InternalCode=n.v.value('(field[#name="InternalCode"]/val)[1]','VARCHAR(40)'),
partnumber=n.v.value('(field[#name="partnumber"]/val)[1]','VARCHAR(40)'),
partdescription=n.v.value('(field[#name="partdescription"]/val)[1]','VARCHAR(40)')
FROM
#i.nodes('/index/doc') AS n(v);
Result:
+-------+--------------+--------------+------------+-----------------+
| rowid | MFG | InternalCode | partnumber | partdescription |
+-------+--------------+--------------+------------+-----------------+
| 0 | ACME | | 012345-00 | PIN |
| 1 | | ABCDE | 919-555-7Z | WASHER |
| 2 | YOUR COMPANY | | 131415 | BOLT |
+-------+--------------+--------------+------------+-----------------+

Related

How to index multi dimension array in solr field

I am indexing Mysql database with solr, I have one-many relation between users table and order table:one user can have many orders.
order table have many columns (id, orderDate, caseNumber).
My goal is to index these tables in solr and have USR_ID field to store the user id, ORDERS feild type= multidimensional array to store each order for that user as an associative array.
the desired result is:
{
"USR_ID":"10",
"ORDERS":[
{"ID":"1" ,"ORDER_DATE":"12-03-2018", "CASE_NUMBER":"554"}, //FIRST FIELD
{"ID":"9","ORDER_DATE":"15-03-2018", "CASE_NUMBER":"569"} //SECOND FIELD
]
}
what i am getting is one dimensional array with all orders columns
{
"USR_ID":"10",
"ORDERS":[
"1", "12-03-2018", "554", //FIRST FIELD
"9", "15-03-2018", "569" //SECOND FIELD
]
}
Here is what I tried.
entities config in data-config.xml
<dataConfig>
<dataSource type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mydb1"
user=""
password=""/>
<document>
<entity name="USERS"
pk="USR_ID"
query="SELECT USR_UID, FROM USERS"
deltaImportQuery="SELECT USR_UID, FROM USERS WHERE USR_UID='${dih.delta.USR_UID}'"
deltaQuery="SELECT USR_UID FROM USERS WHERE USERS.USR_UPDATE_DATE > '${dih.last_index_time}'">
<entity name="ORDER" pk="ID"
query="SELECT ID AS ORDERID, ORDER_DATE, CASE_NUMBER FROM ORDER WHERE USR_ID = '${USERS.USR_UID}'"
deltaQuery="select ID from ORDER where UPDATED_AT > '${dih.last_index_time}'"
parentDeltaQuery="SELECT USR_UID FROM USERS WHERE USR_UID = ${ORDER.USR_UID}">
<field column="ORDERID" name="ORDERS" />
<field column="CREATION_DATE" name="ORDERS" />
<field column="CASE_NUMBER" name="ORDERS" />
</entity>
</entity>
</document>
</dataConfig>
Here is fields definition in schema.xml file
<field name="USR_ID" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<field name="ORDERS" type="text_general" indexed="true" stored="true" required="false" multiValued="true"/>
You will have to go with sub-documents, or at least have one document by order since you only have an Id at the root level :
{
"USR_ID":"10",
"ID":"1" ,
"ORDER_DATE":"12-03-2018",
"CASE_NUMBER":"554"
}
See this good explantion of nested documents :
http://yonik.com/solr-nested-objects/
The answer was to use the following attribute in child="true" field when u define your data-config.xml file
in my case
<entity child="true" name="ORDER" pk="ID"
query="SELECT ID AS ORDERID, ORDER_DATE, CASE_NUMBER FROM ORDER WHERE USR_ID = '${USERS.USR_UID}'"
deltaQuery="select ID from ORDER where UPDATED_AT > '${dih.last_index_time}'"
parentDeltaQuery="SELECT USR_UID FROM USERS WHERE USR_UID = ${ORDER.USR_UID}">
<field column="ORDERID" name="ORDERS" />
<field column="CREATION_DATE" name="ORDERS" />
<field column="CASE_NUMBER" name="ORDERS" />
</entity>

handling null value in nested entity of solr data importer

I'm using the Solr Data Importer to import some category data. I didn't want to use a left join in the parent query because it's too complicated, I preferred to use nested object queries in the configuration to keep it simple.
I've got 3 one to one relationships for feature images of a category. My question is though, how can I handle it when the value in mediaItemX_id field is null? I've tried the nested configuration below, but when the value is null it's reporting invalid sql because the nested query doesn't print null - it prints blank....
<entity name="category" query="SELECT concat('CATEGORY_', c.id) as docId, c.id, externalIdentifier, name, description, shortDescription, mediaItem1_id, mediaItem2_id, mediaItem3_id, created, lastUpdated, keywords, 'CATEGORY' as docType,
name as autoSuggestField
FROM categories c inner join base_content bc where c.id = bc.id">
<field column="id" name="categoryId" />
<field column="externalIdentifier" name="externalIdentifier" />
<field column="docType" name="docType" />
<field column="name" name="name" />
<field column="description" name="description" />
<field column="shortDescription" name="shortDescription" />
<field column="created" name="created" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss" />
<field column="lastUpdated" name="lastUpdated" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss" />
<field column="publishDate" name="publishDate" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss" />
<field column="archiveDate" name="archiveDate" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss" />
<field column="autoSuggestField" name="suburbSuggest" />
<field column="keywords" name="keywords" />
<entity name="mediaItem1" query="SELECT uri, title, altText from media where ${category.mediaItem1_id} is not null and id = ${category.mediaItem1_id}">
<field column="uri" name="featureImage1Url" />
<field column="title" name="featureImage1Title" />
<field column="altText" name="featureImage1AltText" />
</entity>
<entity name="mediaItem2" query="SELECT uri, title, altText from media where ${category.mediaItem2_id} is not null and id = ${category.mediaItem2_id}">
<field column="uri" name="featureImage2Url" />
<field column="title" name="featureImage2Title" />
<field column="altText" name="featureImage2AltText" />
</entity>
<entity name="mediaItem1" query="SELECT uri, title, altText from media where ${category.mediaItem3_id} is not null and id = ${category.mediaItem3_id}">
<field column="uri" name="featureImage3Url" />
<field column="title" name="featureImage3Title" />
<field column="altText" name="featureImage3AltText" />
</entity>
</entity>
Solr supports the notion ${value:default} as replacements in other locations, so I'd try that at least:
${category.mediaItem1_id} IS NOT NULL AND id = ${category.mediaItem1_id:0}
I were unable to find a decent way to skip the entities whole if the current value is false.

Why does the Solr Data Import Handler hashes the uniqueKey?

I have a very strange problem with Solr 4.6.0.
The uniqueKey field "id" contains a hash for every document instead of my string value. If add just one custom document with the update request handler in the Solr admin I get for example the ID value "book_45" that I specified, so that is correct.
But when I do a full import with the DIH (data import handler) then the id field contains a hash for every document like "[B#53bd370f" instead of my custom value. So the problem must be in the DIH.
My import script:
<dataConfig>
<dataSource
type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://host/database"
user="user"
password="password" />
<document name="project">
<entity name="document" transformer="RegexTransformer"
query="SELECT CONCAT('book_', b.id) AS book_id, b.slug, b.title, b.isbn,
b.publisher, b.releaseYear AS release_year, b.language, b.pageCount AS page_count, b.description,
b.print, b.addedBy_id AS added_by_id, b.dt AS created,
GROUP_CONCAT(a.name SEPARATOR ';') AS authors
FROM Book b
LEFT JOIN author_book ab ON ab.book_id = b.id
LEFT JOIN Author a ON a.id = ab.author_id
GROUP BY b.id
">
<field column="book_id" name="id" />
<field column="slug" name="book_slug" />
<field column="title" name="book_title" />
<field column="isbn" name="book_isbn" />
<field column="publisher" name="book_publisher" />
<field column="release_year" name="book_release_year" />
<field column="language" name="book_language" />
<field column="page_count" name="book_page_count" />
<field column="description" name="book_description" />
<field column="print" name="book_print" />
<field column="added_by_id" name="book_added_by_id" />
<field column="created" name="book_created" />
<field column="authors" splitBy=";" name="authors" />
</entity>
</document>
The id field in my schema.xml (which is the same as in the default shipped core collection1):
<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<uniqueKey>id</uniqueKey>
Does anyone know what I am missing?
the [B#53bd370f is not a hash, but the result of a byte[].toString(). Whatever Mysql is returning is being treated as a byte[] instead of a String.
Try casting the id to varchar or char like this:
SELECT cast(CONCAT('book_', b.id) as CHAR) AS book_id...

Solr field depth

How would one set up Solr such that we have "child" node fields?
For example, for this doc, there exists 2 cars, but each car has a subset of colors.
For example:
<doc>
<field name = "make"> Toyota </field>
<field name = "car"> Camri </field>
<field name = "color"> Silver </field>
<field name = "color"> Red </field>
<field name = "car"> Corolla </field>
<field name = "color"> Blue </field>
<field name = "color"> Red </field>
<doc>
How would one go about getting these relationships indexed?
The general practice is to denormalize the database as Solr works with a plain schema. For example, you can make a multi-valued field and put these values into it:
Camri/Silver
Camri/Red
Corolla/Blue
Corolla/Red

xml.value() method in SQL Server (Getting a value inside an XML query)

I have an XML Query like this:
<ChangeSet xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Change DateTime="2011-12-02T09:01:58.3615661-08:00" UserId="3123">
<Table ChangeType="Insert" Name="EVNT_LN_AFF">
<Keys>
<Key FieldName="DIR_CD" Value="NB" />
<Key FieldName="LN_ID" Value="A" />
<Key FieldName="EVNT_ID" Value="10T000289" />
</Keys>
<ChangedFields>
<Field FieldName="DIR_CD" Previous="" Current="NB" />
<Field FieldName="LN_ID" Previous="" Current="A" />
<Field FieldName="EVNT_ID" Previous="" Current="10T000289" />
<Field FieldName="UD_DTTM" Previous="" Current="12/2/2011 9:01:59 AM" />
<Field FieldName="UD_USER_ID" Previous="" Current="3123" />
</ChangedFields>
</Table>
(The query goes on)
Now I want to use a statement like this:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/UD_USER_ID)[0]','varchar(50)') like '%3123%'
But when I execute the query, I don't get any results.
I tested the following XQuery, and it should give you what you need:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/Field[#FieldName="UD_USER_ID"]/#Current)[1]','varchar(50)') like '%3123%'
Note: Indexing for XQuery starts at 1 instead of 0

Resources