<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Ontologize - Medium]]></title>
        <description><![CDATA[Drawing on years of experience with Foundry and in education, we offer premium courses and trainings for Palantir’s Foundry software. Ontologize is not affiliated with Palantir Technologies Inc. - Medium]]></description>
        <link>https://medium.com/ontologize?source=rss----f4dac9f4b9b7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Ontologize - Medium</title>
            <link>https://medium.com/ontologize?source=rss----f4dac9f4b9b7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:37:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ontologize" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Palantir Foundry 101: Intro to Contour for Data Analysis]]></title>
            <link>https://medium.com/ontologize/palantir-foundry-101-intro-to-contour-for-data-analysis-fb486ea1d959?source=rss----f4dac9f4b9b7---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb486ea1d959</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[palantir-foundry]]></category>
            <category><![CDATA[contour]]></category>
            <dc:creator><![CDATA[Taylor Gregoire-Wright]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 16:37:10 GMT</pubDate>
            <atom:updated>2023-07-03T16:37:10.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmhvrWMYAEx5lpzSL4roBw.png" /></figure><h3>What is Contour?</h3><p><a href="https://www.palantir.com/docs/foundry/contour/overview/">Contour</a> is a point-and-click analytics tool in Palantir Foundry. It lets you analyze large-scale tabular data and create interactive dashboards.</p><p>Contour is often one of the first applications in Foundry that new users are exposed to. While some people quickly understand how to use it, many face a steep learning curve because Contour is different from tools they already know.</p><p>Recently I recorded an extensive 40min tutorial, “<a href="https://www.youtube.com/watch?v=3yzenPa5jOQ">Contour 101</a>”, that shows you how to use Contour’s core features. This blog post is a shorter companion piece to that video for anyone who prefers text to video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3yzenPa5jOQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3yzenPa5jOQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3yzenPa5jOQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f766ea365d30cb0c07df7a00fdfb44f/href">https://medium.com/media/1f766ea365d30cb0c07df7a00fdfb44f/href</a></iframe><h3>Contour vs Quiver</h3><p><a href="https://www.palantir.com/docs/foundry/quiver/overview/">Quiver</a>, Foundry’s other main point-and-click analytics tool, is similar to Contour in certain ways. At the surface, both can let you accomplish many of the same tasks: analyze data, create charts, publish interactive dashboards, etc.</p><p>The main difference is in which data you can use in which app (and how they run the computations is different, but that’s beyond the scope of this article).</p><p>If you want to analyze objects in your ontology or you want to work with timeseries data, use Quiver. For datasets, use Contour.</p><h3>Starting an analysis</h3><p>There are two main ways to start an analysis.</p><p>One: open Contour and start a new analysis, then picking the data you want to work with.</p><figure><img alt="Starting a Contour analysis from scratch" src="https://cdn-images-1.medium.com/max/1024/1*I2I1sN6Qb6Epu6m40iYjUA.gif" /></figure><p>Two: find the dataset you want to start with and open it in Contour</p><figure><img alt="Starting a Contour analysis from a dataset" src="https://cdn-images-1.medium.com/max/1024/1*R6arMKbQKLo4a4S6pcomeA.gif" /></figure><p>You can add additional datasets as needed throughout your analysis.</p><h3>Paths &amp; Boards</h3><p>Your Contour analysis is organized into Paths. These are like worksheets in Excel or another spreadsheet software. Each Path starts with one dataset.</p><p>They’re called Paths because you start with the input dataset at the top and add data visualizations and transformations one by one in sequence. Each of these steps in a Path is called a <em>Board</em>.</p><figure><img alt="Scrolling down a Contour analysis Path" src="https://cdn-images-1.medium.com/max/1024/1*5Fm6vQlGvm6wLEQRZfAxMA.gif" /></figure><p>For example, you might first add a Filter Board to get rid of some rows. Then you might add a Chart Board to plot the data. If you then change what you’re filtering on, the chart will update to show the new data. Everything runs top to bottom. If you add another Filter Board below the chart, there’s no way for that filter to affect the chart due to where it sits in the Path.</p><figure><img alt="A filter board then a chart board then another filter board" src="https://cdn-images-1.medium.com/max/1024/1*JxPH8Rp8B80e-CGe27-hoQ.gif" /></figure><h3>Boards that <em>Display</em> data vs. Boards that Transform data</h3><p>Although the Boards menu has several categories, I typically think about just two: Boards that <em>display</em> data and Boards that <em>transform</em> data.</p><p>An example of a Display Board is the Table. It just shows the data in a table and doesn’t change the data in any way.</p><figure><img alt="A table board in Contour" src="https://cdn-images-1.medium.com/max/1024/1*AAA3FsZ2-LTjLoWyAGhaJA.png" /></figure><p>An example of a Transform Board is the Filter. It changes the data by removing rows that meet whatever criteria you specify. Another example is the Join Board, which changes the data by adding columns from another dataset.</p><figure><img alt="A join board in Contour" src="https://cdn-images-1.medium.com/max/1024/1*DHX1RulnHYyYX9dq2LKxGQ.png" /></figure><p>The reason I group Boards into Display and Transform categories is because in my experience, one point of confusion for people is the fact that some Boards (the Transform Boards) affect the in Boards below them while other boards (the Display Boards) don’t.</p><p>For example, someone might add a Filter to check something specific about the data but then forget that it still applies as they continue adding more Boards. Those Boards will seem incorrect but the user won’t realize that it’s because the Filter board they added above is affecting everything below it.</p><h4>Some Boards can do both</h4><p>The Pivot Table can display data in a pivot table format <em>and</em> it can change the shape of the data if you click that option. Or, the Chart board can filter data if you select data in the chart.</p><figure><img alt="Changing between pivoted and normal data" src="https://cdn-images-1.medium.com/max/1024/1*HJ5PllLn9BZ44REXgpbz6w.gif" /></figure><h3>Saving Datasets</h3><p>At the bottom of your analysis is the ever-present Results Board. It represents the current state of the input data after applying all the transformations (Boards) in your Path.</p><p>You can save this as a new <em>Dataset</em>, which is handy if you want to use this data in another application, export it from Foundry, preserve it for future analysis, or create a clean dataset specific to your team’s needs.</p><p>When you save a Dataset, Foundry will use the logic of that Path to <em>Build</em> the Dataset. That is, it will run all the Transform Boards in order and save the output in the Dataset you just created.</p><figure><img alt="Saving a new dataset from Contour" src="https://cdn-images-1.medium.com/max/1024/1*J0lo3a4IU5_JyeEeidqLUQ.gif" /></figure><h3>Dashboards</h3><p>Contour also lets you create <em>Dashboards</em>. Each Contour Analysis lets you create one Dashboard.</p><p>You can add Boards to your Dashboard by clicking the “Add to Dashboard” button. Only Display Boards have this button.</p><p>On the left-hand side of your screen you have a list of Boards in your Dashboard.</p><figure><img alt="Adding boards to a dashboard" src="https://cdn-images-1.medium.com/max/1024/1*W4ACG7ydUuoFFr0fglZGJg.png" /></figure><p>When you enter the Dashboard, you can move Boards around, change titles, add text, and prepare your Dashboard for others to use. Dashboards intentionally have relatively limited formatting capabilities. If you need something pixel-perfect, you may want to consider another tool such as Slate (which is normally for app building, but can also be used for dashboards) or an external tool that connects to Foundry such as PowerBI.</p><h3>Parameters</h3><p>Parameters let you define a value in one place and use it multiple times throughout your analysis. Parameters are especially useful for making Dashboards more engaging.</p><p>For example, in the video tutorial I create a state parameter that lets uses pick multiple states from a list of all US states. The charts in the Dashboard then update to show only data for those states.</p><figure><img alt="Changing parameter values in a Contour dashboard" src="https://cdn-images-1.medium.com/max/1024/1*TMd85gmTKI-8YkzANxPAbw.gif" /></figure><p>You can also use Parameters in your analysis. For example, if you need to filter data but you need to try many values to figure out what the right one should be, using a Parameter in the Filter Board will save you from having to open the Path that has that Board, scroll to the Board, click to edit the Board…you get the point.</p><h3>Sharing Your Analysis</h3><p>You can share your analysis so that others either have edit access or just view access.</p><p>For Dashboards, you probably want to share view access so that colleagues can interact with the data by changing parameter values (for only themselves), but not edit the underlying analysis. You can easily do that by sharing a link to your analysis. If you want people to open the analysis in dashboard mode, you can change that in the settings panel.</p><figure><img alt="Sharing view-only access to a Contour analysis" src="https://cdn-images-1.medium.com/max/1024/1*miPW52nlDnwzp_9rlcubGw.png" /></figure><p>You can send a particular view of the Dashboard to someone by sharing a link generated by this button in the Parameters panel.</p><figure><img alt="Sharing a link to a specific view in Contour" src="https://cdn-images-1.medium.com/max/1024/1*1z5xbgjfGZf2ErLXraNTrQ.png" /></figure><p>If you want to collaborate on the analysis with someone else, you should grant them editor permissions. If the project you saved the analysis in gives edit permissions to your teammates by default, then they will already be able to edit your analysis.</p><p>Additionally, you can set the analysis to open in viewing mode by default. This is useful for analysis that you do want people to have edit access to, but which shouldn’t normally be changed.</p><figure><img alt="Toggling Contour’s View-only mode" src="https://cdn-images-1.medium.com/max/1024/1*ZscD1bAeYzzNQ1a7-b3p4Q.png" /></figure><h3>Parting Thoughts</h3><p>This post is just a quick summary of how to get started with Contour. I’ve seen people make some incredibly sophisticated and influential analyses in Contour once they’ve worked with it for a while and learned its more advanced capabilities.</p><p>Let me know if this raises any questions about Foundry that you’d like answered — you can email me at <a href="https://medium.com/taylor@ontologize.com">taylor@ontologize.com</a> or message me on <a href="https://www.linkedin.com/in/tgregoirewright/">LinkedIn</a> with suggestions for future tutorials.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb486ea1d959" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ontologize/palantir-foundry-101-intro-to-contour-for-data-analysis-fb486ea1d959">Palantir Foundry 101: Intro to Contour for Data Analysis</a> was originally published in <a href="https://medium.com/ontologize">Ontologize</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Contour: big data analytics in Foundry]]></title>
            <link>https://medium.com/ontologize/intro-to-contour-big-data-analytics-in-foundry-4d89c2c14e6a?source=rss----f4dac9f4b9b7---4</link>
            <guid isPermaLink="false">https://medium.com/p/4d89c2c14e6a</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[palantir]]></category>
            <dc:creator><![CDATA[Taylor Gregoire-Wright]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 17:47:46 GMT</pubDate>
            <atom:updated>2023-06-12T17:47:30.009Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3yzenPa5jOQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3yzenPa5jOQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3yzenPa5jOQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8adf7e84e5a133151e18c597741a9067/href">https://medium.com/media/8adf7e84e5a133151e18c597741a9067/href</a></iframe><p>Contour is a powerful analytical application in Foundry. It gives you an efficient point-and-click way of transforming and visualizing large scale datasets. You don’t need to think about managing compute resources, and you don’t need to circumvent data security rules in order to create and share analyses — all the important background stuff is handled by Foundry’s core infrastructure.</p><p>However, Contour is sufficiently different from other analytical tools that it can be tricky to learn on your own. I’ve created a Contour 101 video for anyone looking to get started with Contour. It’s a friendly way of going from a blank slate to your first analytical product in under an hour.</p><p>Let me know if you’ve got any questions or suggestions for future posts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d89c2c14e6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ontologize/intro-to-contour-big-data-analytics-in-foundry-4d89c2c14e6a">Intro to Contour: big data analytics in Foundry</a> was originally published in <a href="https://medium.com/ontologize">Ontologize</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Typescript Interfaces for Foundry Object Types]]></title>
            <link>https://medium.com/ontologize/generate-typescript-interfaces-for-foundry-object-types-62ec253eed74?source=rss----f4dac9f4b9b7---4</link>
            <guid isPermaLink="false">https://medium.com/p/62ec253eed74</guid>
            <category><![CDATA[foundry-apis]]></category>
            <category><![CDATA[palantir-foundry]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ontology]]></category>
            <dc:creator><![CDATA[Taylor Gregoire-Wright]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 22:18:38 GMT</pubDate>
            <atom:updated>2023-04-28T22:17:48.302Z</atom:updated>
            <content:encoded><![CDATA[<p>When using Typescript to build an app that uses Foundry’s ontology APIs, you’ll need interface definitions for your object types. While it doesn’t take very long to create these manually, we use a <a href="https://github.com/ontologize/generate-object-typings">small script</a> to automatically generate object type definitions by calling Foundry’s <a href="https://proper-raindrop.palantirfoundry.com/documentation/static/foundry/api/ontology-resources/object-types/get-object-type/">get object type endpoint</a>.</p><figure><img alt="Screenshot of an object type interface definition printed to the console." src="https://cdn-images-1.medium.com/max/1024/1*F-x-pnISgkGBUlJ0RycLJg.png" /></figure><h4>Setup</h4><p>This script is written in Typescript and uses <a href="https://deno.land/">Deno</a>, a Typescript runtime. After cloning the repo and <a href="https://deno.land/manual/getting_started/installation">installing Deno</a> on your machine, you’ll need to create some environment variables.</p><p><a href="https://www.palantir.com/docs/foundry/api/general/overview/authentication/#authentication-during-development">Generate a Foundry API token</a>, and store it in an environment variable called TOKEN. Also store the hostname of your stack and the ontology rid for the relevant ontology. You can find the ontology rid in the Advanced pane of the Ontology Manager app:</p><pre>export $TOKEN=&lt;your foundry token&gt;<br>export $HOSTNAME=&lt;your hostname&gt;  # often in the form something.palantirfoundry.com<br>export $ONTOLOGYRID=&lt;your ontology rid&gt;</pre><p>Alternately, create a .env file and add your token there:</p><pre># ./.env<br><br>TOKEN=&lt;your foundry token&gt;<br>HOSTNAME=&lt;your hostname&gt;<br>ONTOLOGYRID=&lt;your ontology rid&gt;</pre><h4>Usage</h4><p>To use the script, run the following command. It will print out the interface definitions for each object type you supply. You can then copy the definitions wherever you need them. All properties except the primary key will be typed as optional. Properties will remain in the same order as received in the response from Foundry’s API.</p><p>Use the -o or --objectTypes option before the object types.</p><pre>$ deno --allow-net run generateObjectTypings -o &lt;objectType1ApiName&gt; &lt;objectType2ApiName&gt; ...</pre><p>It will print the interface definitions:</p><pre>interface ObjectType1 {<br>  propPrimaryKey: someType;<br>  prop2?: someType;<br>  prop3?: someType;<br>  ...<br>}</pre><h3>Options</h3><ul><li>If you want to extend a generic OntologyObject interface, add the -e or --extendOntologyObject option. This option is incompatible with the -t option and will be overridden by that option.</li></ul><figure><img alt="Screenshot of an object type interface definition that extends an OntologyObject interface definition." src="https://cdn-images-1.medium.com/max/902/1*rybGOvHUB2_D0nQ8FEygfg.png" /></figure><ul><li>If you want types instead of interfaces, add the -t or --types option.</li><li>If you want the original object types included as comments, add the -c or --commentOntologyType option.</li><li>If you want to type date and timestamp fields as strings instead of Date, add the -d or --ateAsString option.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ec253eed74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ontologize/generate-typescript-interfaces-for-foundry-object-types-62ec253eed74">Generate Typescript Interfaces for Foundry Object Types</a> was originally published in <a href="https://medium.com/ontologize">Ontologize</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a search feature for Foundry’s ontology]]></title>
            <link>https://medium.com/ontologize/how-to-build-a-search-feature-for-foundrys-ontology-c4c50cf3db06?source=rss----f4dac9f4b9b7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c4c50cf3db06</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[palantir-foundry]]></category>
            <dc:creator><![CDATA[Taylor Gregoire-Wright]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 18:42:59 GMT</pubDate>
            <atom:updated>2023-05-02T16:18:51.319Z</atom:updated>
            <content:encoded><![CDATA[<p>This article demonstrates how to build a search feature for a web app that uses <a href="https://www.palantir.com/docs/foundry/ontology/overview/">Foundry’s ontology</a>.</p><p>You can find the example code on <a href="https://github.com/ontologize/search-demo">GitHub</a>. While this project uses Typescript and React, most of the points covered here are relevant to other tech stacks even if the code is not.</p><p>First we build a simple search feature that lets users search one property of one object type. Then we modify that feature to enable searching multiple properties of that object type. Finally, we create a live search experience where results appear as the user is typing. In a future article, we will cover searching across multiple object types simultaneously.</p><p>However, before we start coding we need to clarify just what we mean by “search”.</p><h3>Searching vs. Filtering</h3><p>Both searching and filtering are ubiquitous, but from a user’s perspective they are not the same. Some distinguishing characteristics are:</p><p><strong>Starting point</strong></p><ul><li>Search experiences usually start from a blank slate and add results.</li><li>Filtering experiences usually start from a set of results and winnow them down.</li></ul><p><strong>Relevance</strong></p><ul><li>Search has some notion of relevance.</li><li>Filtering usually allows users to sort results, but there’s rarely any intrinsic sense of relevancy to the sort order.</li></ul><p><strong>Knowledge of the data model</strong></p><ul><li>Search doesn’t require users to be aware of the data model of the things they’re looking for.</li><li>Filtering does require users to have a sense of the dimensions along which the results can be described (e.g. in the context of the pants section of an online clothing store, a user should understand what the filter for inseam length refers to).</li></ul><p>Despite these differences, search and filtering often appear side by side. For example:</p><ul><li>Google Image Search returns images ranked by relevance and then lets you filter by aspects such as color and size</li><li><a href="https://www.mcmaster.com/">McMaster-Carr</a> lets you search for a part or product and then offers detailed filtering options depending on what the search results are</li><li>The <a href="https://www.loc.gov/">US Library of Congress search</a> applies a filter by default, “Available Online”, and offers additional filter options on the results page</li></ul><figure><img alt="Video of searching the McMaster-Carr website for “leaf springs”. The left-hand filter updates with filters specific to the characteristics of leaf springs and related product results, such as spring steel." src="https://cdn-images-1.medium.com/max/1024/1*6KgpO9pbvkzV6GKHTAVVmg.gif" /></figure><p>Sometimes, search appears alone. This is common in documentation sites, such as the <a href="https://tailwindcss.com/">TailwindCSS docs</a>, the <a href="https://spark.apache.org/docs/latest/index.html">Apache Spark docs</a>, or the <a href="https://www.palantir.com/docs">Foundry docs</a>. This is what we will be building.</p><p>Understanding how search differs from filtering helps us deconstruct our desired user experience into specific requirements. We want to let users input a query term and receive results sorted by relevance; users should not need to understand the data model of that object type beforehand.</p><h3>Foundry’s Ontology APIs</h3><p>How many of those requirements can we achieve using Foundry’s ontology APIs?</p><p>The relevant endpoint is <a href="https://www.palantir.com/docs/foundry/api/ontology-resources/objects/search/">/search</a>. To use it, you specify the object type in the url and you include a query in the request body. Optionally, the request body can also include the page size and instructions for how to sort the results.</p><h4>Queries</h4><p>Queries have three parts: type, field, and value. <a href="https://www.palantir.com/docs/foundry/api/ontology-resources/objects/search/#query-types">Type</a> refers to which operator is used, such as “exactly equal to” or “contains all terms”. Field is which property on the object type is being checked. Value is the query term the user types into our search bar.</p><pre>{<br>  type: &quot;allTerms&quot;,<br>  field: &quot;properties.component&quot;,<br>  value: &quot;seatbelt&quot;,<br>}</pre><p>Queries can be nested.</p><pre>{<br>  type: &quot;or&quot;,<br>  value: [<br>    { type: &quot;anyTerms&quot;, field: &quot;properties.subject&quot;, value: &quot;recall repair&quot; },<br>    { type: &quot;allTerm&quot;, field: &quot;properties.component&quot;, value: &quot;seatbelt&quot; }<br>  ]<br>}</pre><p>Looking at the available <a href="https://www.palantir.com/docs/foundry/api/ontology-resources/objects/search/#query-types">query types</a>, we can see that our search feature can only be as sophisticated as combinations of these operators will allow.</p><p>While we can do things like matching phrases or checking that at least one word of the query term is present, we can’t do things like accommodating typos or searching for synonyms. We will need to keep this in mind when building our search feature.</p><h4>Ordering</h4><p>By including an ordering field in the request body, we can sort the results. We can order by the values of existing properties. We don’t have the ability to order by values computed on the fly. The docs include more details on ordering under the <a href="https://www.palantir.com/docs/foundry/api/ontology-resources/objects/list-objects/#query-parameters">query parameters section of the list objects endpoint</a>.</p><p>In this example project, we will not use ordering because ordering by existing properties will not help us rank search results by relevance. Ordering is typically more useful in the context of filter features.</p><h4>Our plan</h4><p>Using the /search endpoint of Foundry’s ontology APIs, we will be able to build a search feature that lets users search for objects without knowing its data model ahead of time. We won’t be able to rank search results by relevancy.</p><p>We will be able to customize the <a href="https://en.wikipedia.org/wiki/Precision_and_recall">precision and recall</a> of our search feature within the bounds of the available query types — we could be very precise by using “exactly equals” or we could have high recall by using “contains at least one of the terms”. We won’t be able to handle typos.</p><p>We will start with a simple search experience where the user inputs a query term and clicks a button to search.</p><h3>Setup</h3><p>Our goal is to let users search US vehicle recalls. The source of this data is the <a href="https://www.nhtsa.gov/nhtsa-datasets-and-apis#recalls">US National Highway Traffic Safety Administration</a>. We have created a Vehicle Recall object type in our ontology.</p><figure><img alt="Screenshot of Foundry’s Ontology Manager application showing the VehicleRecall object type’s configuration page." src="https://cdn-images-1.medium.com/max/1024/1*x3oDYgir6kl5fV_Z8qPMcQ.png" /></figure><p>In this first attempt, we will be searching a single property, the Complaint subject. Examples of subjects are “Fuel line leakage”, “Steering gears”, and “Converter neutral wire”.</p><h3>Project Setup</h3><p>Clone the <a href="https://github.com/ontologize/search-demo">search-demo repository</a> and create a .env.local file, which will be excluded from version control. In that file, add the following environment variables. You’ll need to get a <a href="https://www.palantir.com/docs/foundry/api/general/overview/authentication/#authentication-during-development">developer token from Foundry’s settings page</a>.</p><pre># /.env.local<br><br>TOKEN=&lt;your-foundry-token&gt;<br>NEXT_PUBLIC_HOSTNAME=&lt;your-foundry-hostname&gt;<br>ONTOLOGYRID=&lt;your-ontology-rid&gt;</pre><p>Install the dependencies. This demo uses <a href="https://pnpm.io/installation#using-npm">pnpm</a> for package management, but if you prefer npm or yarn those should work fine too.</p><h3>Vehicle Recall Object Type</h3><p>If you haven’t already created a Vehicle Recall object type in your ontology, do that now. If your Vehicle Recall object type has a different API name than VehicleRecall, you will need to change all instances of VehicleRecall in the code to whatever your API name is for the Vehicle Recall object type.</p><p>You can download the NHTSA Vehicle Recall data from the repo as either <a href="https://github.com/ontologize/search-demo/blob/main/nhtsa_vehicle_recall.csv">csv</a> or <a href="https://github.com/ontologize/search-demo/blob/main/nhtsa_vehicle_recall.xlsx">excel</a> files. You can upload either of them to Foundry and use that dataset to back you Vehicle Recall object type.</p><p>In the /src/types.ts file we have already included an interface for the Vehicle Recall object type. If you omit any properties from the version in your ontology or if you change any property names, you’ll need to update this interface definition.</p><p>You can, of course, use an existing object type provided that you update the code accordingly. In particular you’ll need to:</p><ul><li>Add an interface definition for your object type in /src/types.ts</li><li>Replace instances of VehicleRecall with your object type’s API name</li></ul><h3>Verify the Setup</h3><p>By this point you have:</p><ul><li>Cloned the repo and installed the dependencies</li><li>Added a .env.local file with all required environment variables</li><li>Created a Vehicle Recall object type in your ontology and updated the code if you used a different API name than VehicleRecall</li></ul><p>Next, start the server with pnpm dev and verify that you see the Search Demo landing page at <a href="http://localhost:3000/">http://localhost:3000</a>. You should be able to search the Vehicle Recall objects at <a href="http://localhost:3000/simple">http://localhost:3000/simple</a>.</p><figure><img alt="Screencast of a user typing a search term into the app and scrolling through the results." src="https://cdn-images-1.medium.com/max/1024/1*9YnZmyx6GoZ6aPdHrmcMIA.gif" /></figure><h3>Part 1: Simple Search</h3><p>Checkout the tutorial branch to get started. You can refer to the main branch for the final code whenever you want.</p><p><em>Note: This project uses Next.js, which organizes routes using a file structure. You can learn more in the </em><a href="https://beta.nextjs.org/docs/routing/route-handlers"><em>Next.js docs</em></a><em>.</em></p><h3>Searching</h3><p>If you start the server and navigate to /simple you’ll see that we have the page title and some text, but nothing else. First, let’s add a search bar using the &lt;SearchBar /&gt; components in /src/components.</p><pre>//  /src/app/simple/page.tsx<br><br>&lt;SearchBar<br>  queryTerm={queryTerm}<br>  handleSearch={handleSearch}<br>  setQueryTerm={setQueryTermTerm}<br>  isSearching={isSearching}<br>/&gt;</pre><p>We can see that we’ll also need to track the text the user has typed into the search bar. We’ll use React’s useState hook for that.</p><pre>const [queryTerm, setQueryTermTerm] = useState&lt;string&gt;(&quot;&quot;);</pre><p>Additionally, we need a function, handleSearch, to run when the user clicks the “Search” button. If the input is empty nothing should happen, but if there’s a value then we want to run the search. We’re using a second function, fetchResults, to make the API call because we also want that function available when users click a button to load more results.</p><pre>function handleSearch() {<br>  if (queryTerm !== &quot;&quot;) {<br>    fetchResults();<br>  }<br>}</pre><p>The fetchResults function needs to call our app’s API that handles communicating with Foundry’s ontology APIs. We will build our app’s API in a moment. For now, we need to construct a search query, post that to our app’s API, save the search results, and update any other state variables that need to change after the search is complete.</p><p>The Simple Search page of our app will only search a single property, so our query can be quite simple. We’ve chosen to use the allTerms operator on the subject property of the VehicleRecall object type. You can experiment with a different operator or property to search over.</p><pre>const query: Query = {<br>  type: &quot;allTerms&quot;,<br>  field: &quot;properties.subject&quot;,<br>  value: queryTerm,<br>};</pre><p>So far, our fetchResults() function looks like this:</p><pre>async function fetchResults() {<br>  const query: Query = {<br>    type: &quot;allTerms&quot;,<br>    field: &quot;properties.subject&quot;,<br>    value: queryTerm,<br>  };<br>}</pre><p>It doesn’t yet do anything, so let’s fix that by calling our soon-to-be-created /search endpoint.</p><pre>async function fetchResults() {<br>  const query: Query = {<br>    type: &quot;allTerms&quot;,<br>    field: &quot;properties.subject&quot;,<br>    value: queryTerm,<br>  };<br><br>  fetch(`/api/search?objectType=${objectType}`, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({ query, pageSize, pageToken: nextPageToken }),<br>  })<br>    .then((resp) =&gt; resp.json())<br>    .then((respJson) =&gt; {<br>      setResults([...results, ...respJson[&quot;data&quot;]]);<br>      setNextPageToken(respJson[&quot;nextPageToken&quot;]);<br>      setIsSearching(false);<br>    });<br>}</pre><p><em>The function passes an object type in the URL’s query parameters. That’s not strictly necessary for this demo since we’re only searching a single object type, but in a future article we will show how to search over multiple object types.</em></p><p>Several variables required by this function are missing, so let’s add them and review why we need them.</p><p>First, although a page size value is optional, it’s good practice to add it if you have that option. Foundry’s /search endpoint does let us <a href="https://www.palantir.com/docs/foundry/api/ontology-resources/objects/search/#example-search-requests">specify a page size</a>, and I’ve set it at 10.</p><pre>const pageSize = 10;</pre><p>Next, we need a way to store the search results. We can do that with a list of VehicleRecall objects. In our fetchResults function, we set the results variable to a new array of all the existing results and the newly returned results.</p><pre>const [results, setResults] = useState&lt;VehicleRecall[]&gt;([]);</pre><p>Next, we need a way to store the search results. We can do that with a list of VehicleRecall objects. In our fetchResults function, we set the results variable to a new array of all the existing results and the newly returned results.</p><pre>const [results, setResults] = useState&lt;VehicleRecall[]&gt;([]);</pre><p>Finally, we need to store the nextPageToken value. Foundry endpoints paginate results and use the common method of returning a token to the client to use on its next request.</p><pre>const [nextPageToken, setNextPageToken] = useState&lt;string | undefined&gt;();</pre><p>Now, our function should be free of errors. However, since we’re working with React we need to refactor our function slightly so that it’s aware of the latest values of our stateful variables such as queryTerm. To do that, we use the useCallback hook, which you can read more about in the <a href="https://react.dev/reference/react/useCallback">React docs</a>.</p><pre>const fetchResults = useCallback(async () =&gt; {<br>  const query: Query = {<br>    type: &quot;allTerms&quot;,<br>    field: &quot;properties.subject&quot;,<br>    value: queryTerm,<br>  };<br><br>  fetch(`/api/search?objectType=${objectType}`, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({ query, pageSize, pageToken: nextPageToken }),<br>  })<br>    .then((resp) =&gt; resp.json())<br>    .then((respJson) =&gt; {<br>      setResults([...results, ...respJson[&quot;data&quot;]]);<br>      setNextPageToken(respJson[&quot;nextPageToken&quot;]);<br>      setIsSearching(false);<br>    });<br>}, [queryTerm, nextPageToken, results]);</pre><p>With our fetchResults function done, we need to return to our handleSearch function. It does not behave correctly when the user has already searched for some other term. That’s because of how the fetchResults function appends new results to the current ones and passes in the nextPageToken. If there are already results from a previous search, those results will remain. If there’s a page token from a previous search, that will cause an error. A solution is simply to reset the search results and page token.</p><pre>function handleSearch() {<br>  if (queryTerm !== &quot;&quot;) {<br>    setIsSearching(true);<br>    setResults([]);<br>    setNextPageToken(undefined);<br>    fetchResults();<br>  }<br>}</pre><p>And, for a better user experience, let’s clear all results if the user clears the text in the search bar.</p><pre>useEffect(() =&gt; {<br>  if (queryTerm === &quot;&quot;) {<br>    setResults([]);<br>    setNextPageToken(undefined);<br>  }<br>}, [queryTerm]);</pre><h4>Our app’s /search endpoint</h4><p>Before displaying the list of search results, we will create our app’s /search endpoint. It will accept a POST request from our front-end and make a POST request to Foundry’s API to execute the search. Note that in a real app you would want to include proper error handling.</p><pre>export async function POST(request: Request) {<br>  const body = await request.json();<br>  const objectType = new URL(request.url).searchParams.get(&quot;objectType&quot;);<br>  if (objectType) {<br>    const url = `https://${process.env.NEXT_PUBLIC_HOSTNAME}/api/v1/ontologies/${process.env.ONTOLOGYRID}/objects/${objectType}/search/`;<br>    return await fetch(url, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        Authorization: `Bearer ${process.env.TOKEN}`,<br>      },<br>      body: JSON.stringify(body),<br>    })<br>      .then((resp) =&gt; resp.json())<br>      .then((respJson) =&gt; NextResponse.json(respJson));<br>  }<br>}</pre><p>At this point, the search bar should work. However, no results appear on the page.</p><h4>Adding a Results List</h4><p>Returning to our /src/app/simple/page.tsx file, we want to use the &lt;ResultsList /&gt; component to display the search results.</p><pre>// /src/app/simple/page.tsx<br><br>export default function SimpleSearch() {<br>  ...<br>  return (<br>    ...<br>    &lt;ResultsList results={results} /&gt;<br>  ...<br>}</pre><p>Now, you should be able to successfully search for Vehicle Recalls and see the results appear. To wrap up this simple example, we just need to add the ability to load more results. The code already has a “Load More” button that displays a loading spinner when the isSearching variable equals true. Functionally, it currently only serves to give feedback to the user that a search is running. It should also display when there are more pages of results to fetch even if the user is not waiting for the search to execute.</p><figure><img alt="Screencast of a user searching for the term “seatbelt”, scrolling through the results, and loading more results." src="https://cdn-images-1.medium.com/max/1024/1*P-hlWLCnbs2R4aiEohwtEQ.gif" /></figure><p>Modifying the logic to check the truthiness of either nextPageToken or isSearching will achieve that. And, since our fetchResults function already uses the nextPageToken, adding a call to fetchResults in the Load More button’s onClick prop will add the next page of results to our list.</p><pre>&lt;ResultsList results={results} /&gt;<br>  {(nextPageToken || isSearching) &amp;&amp; (<br>    &lt;button<br>      className=&quot;...&quot;<br>      onClick={() =&gt; {<br>        setIsSearching(true);<br>        fetchResults();<br>      }}<br>    &gt;<br>      {isSearching ? &lt;LoadingSpinner colorVariant=&quot;cyan&quot; /&gt; : &quot;Load More&quot;}<br>    &lt;/button&gt;<br>  )}</pre><h3>Part 2: Multi-property Search</h3><p>We just saw how to build a search bar that lets users search across a single property of an object type. Now we’ll make our query more sophisticated to allow searching across multiple properties. Searching multiple properties requires changing just the query our app sends to Foundry. Otherwise the code is the same as in Part 1: Simple Search.</p><p>Copy the code from /src/app/simple/page.tsx into a new page.tsx in /src/app/multi-prop. The only part we will change is the query variable in the fetchResults function. For the sake of illustrating more types of operators and how to combine sub-queries, this query is somewhat contrived. However, in real applications queries may need to be rather complicated in order to enable the desired search functionality.</p><pre>const query: Query = {<br>  type: &quot;or&quot;,<br>  value: [<br>    { type: &quot;allTerms&quot;, field: &quot;properties.subject&quot;, value: queryTerm },<br>    { type: &quot;anyTerm&quot;, field: &quot;properties.component&quot;, value: queryTerm },<br>    {<br>      type: &quot;allTerms&quot;,<br>      field: &quot;properties.consequenceSummary&quot;,<br>      value: queryTerm,<br>    },<br>    {<br>      type: &quot;allTerms&quot;,<br>      field: &quot;properties.correctiveAction&quot;,<br>      value: queryTerm,<br>    },<br>    {<br>      type: &quot;eq&quot;,<br>      field: &quot;properties.recallType&quot;,<br>      value: queryTerm<br>        .split(&quot; &quot;)<br>        .map(<br>          (s) =&gt;<br>            s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase()<br>        )<br>        .join(&quot; &quot;),<br>    },<br>    {<br>      type: &quot;eq&quot;,<br>      field: &quot;properties.nhtsaId&quot;,<br>      value: queryTerm,<br>    },<br>    {<br>      type: &quot;and&quot;,<br>      value: [<br>        {<br>          type: &quot;anyTerm&quot;,<br>          field: &quot;properties.recallDescription&quot;,<br>          value: queryTerm,<br>        },<br>        {<br>          type: &quot;anyTerm&quot;,<br>          field: &quot;properties.manufacturer&quot;,<br>          value: queryTerm,<br>        },<br>      ],<br>    },<br>  ],<br>};</pre><h4>Notes on the query</h4><p>There are a few points to highlight about this query. First, and and or operators require lists of queries. Along with not, these allow for very sophisticated queries to be constructed.</p><p>Second, though we have written out the queries manually for sake of demonstration, it’s often helpful to rely on functions that dynamically construct queries. In fact, this is essential if you want to build advanced filtering features, such as what travel sites like Expedia or Booking.com offer their users. Refer to the Query interface definition in /src/types.ts for one way to type inputs to such a builder function.</p><p>Third, it’s vital to check which query types are case sensitive. For example, eq is case sensitive, which presents a challenge for searching the RecallType property. All RecallType words begin with an uppercase letter. One option is to modify the data in the pipeline backing our Vehicle Recall object type, but many times that’s not an option. Other users may depend on the particular formatting of this property for unrelated workflows. Instead, we process each part of the user’s query term prior to running the search in Foundry. More complicated transformations might deserve stand-alone functions.</p><h4>Part 3: Live Search</h4><p>Letting a user click a button to run a search is perfectly functional, but sometimes we want to provide a different user experience. Type-ahead or live search is one such option — results appear as the user types.</p><figure><img alt="Screencast of a user searching for “gasoline” with results loading as the user types." src="https://cdn-images-1.medium.com/max/1024/1*cqiO5sZ_OYdMjKfB1jm2lg.gif" /></figure><p>When it comes to interacting with Foundry, live search is conceptually very similar to our simple and multi-property search features. Therefore, we won’t be reviewing most of the code changes as they are React-specific. One point worth noting is that if you build a live search feature, it’s important to debounce your requests so that your app doesn’t send needlessly many requests.</p><p>Refer to the /src/app/live/page.tsx file on the main branch for the code. The main changes are wrapping the search function in a useEffect hook, memoizing the query, and adding a named handleLoadMore function.</p><h3>Where to go from here</h3><p>Our search feature works, but it does have one notable shortcoming. The results are not sorted by their relevance to the user’s query.</p><p>Our suggestion is to embrace what Foundry does offer, sophisticated filtering capabilities in this case, and try to design user experiences that maximize those capabilities. For example, it might be possible to design a UI that encourages quick and aggressive pruning of search results via filters. Along with large page sizes, that could allow for your app to handle relevancy ranking.</p><p>In a future post, we will show how to simultaneously search multiple object types.</p><p>In the meantime, there are several ways you can extend this search feature to meet the needs of your organization, including:</p><ul><li>Adding the ability to filter results, which would require dynamically constructing the query in response to user selections of which filters to apply and what values to provide those filters.</li><li>Adding error handling and better handling of bad states (e.g. a better no results message)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c50cf3db06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ontologize/how-to-build-a-search-feature-for-foundrys-ontology-c4c50cf3db06">How to build a search feature for Foundry’s ontology</a> was originally published in <a href="https://medium.com/ontologize">Ontologize</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>