PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
SELECT ?type ( SAMPLE( ?label ) AS ?typeLabel ) ( COUNT( DISTINCT ?org ) AS ?count ) WHERE {
  VALUES ?region {
    wd:Q107356467
  }
  ?org wdt:P31 ?type .
  {
    ?org wdt:P131 * ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131 * ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131 * ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131 * ?region .
  }
  ?type wdt:P279 * wd:Q43229 .
  OPTIONAL {
    ?type rdfs:label ?label .
    FILTER ( LANG( ?label ) = "en" )
  }
}
GROUP BY ?type
ORDER BY DESC ( ?count )

Using entities:
- Balearic Islands (wd:Q107356467): is instance of autonomous community of Spain / is instance of historical nationality / autonomous community of Spain
- organization (wd:Q43229), also known as institution, organisation, organisations, organization in sociology, organizations: is instance of social science concept / is subclass of person or organisation / is subclass of person or organization / is subclass of corporate body / is subclass of group of humans / is subclass of social system / is subclass of complex system / social entity established to meet needs or pursue goals / social entity with a collective goal / social entity with a collective goal / social entity with a collective goal

Using properties:
- located in the administrative territorial entity (wd:P131 as wdt), also known as administrative territorial entity, administrative territory, city, happens in, in, etc.: is subproperty of location / is subproperty of part of / the item is located on the territory of the following administrative entity / the item is located on the territory of the following administrative entity / the item is located on the territory of the following ... the item falls only partially into the administrative entity. / the item is located on the territory of the following ... the item falls only partially into the administrative entity.
- headquarters location (wd:P159 as wdt), also known as admin HQ, based in, garrison, head office location, head quarters, etc.: is subproperty of significant place / city or town where an organization's headquarters is or has been situated. Use P276 qualifier for specific building / specific location where an organisation's HQ is or has been located / specific location where an organisation's HQ is or has been located
- location (wd:P276 as wdt), also known as based in, city, from, held by, in, etc.: location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706. / location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706. / location of the object, structure or event. In the case of an ... use P706. Use P7153 for locations associated with the object
- subclass of (wd:P279 as wdt), also known as all members of this class also belong to, category of, form of, has superclass, is a class of, etc.: this item is a subclass (subset) of that item; ALL instances ... of volcanic landform); Everest is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain
- instance of (wd:P31 as wdt), also known as example of, has type, is a, is an, is of type, etc.: that class of which this subject is a particular example and ... a subclass of mountain (and an instance of volcanic landform) / type to which this subject corresponds/belongs. Different ... and the volcano is a type (instance) of volcanic landform
- location of formation (wd:P740 as wdt), also known as comes from, formation location, formation place, formed in, founded in, etc.: is subproperty of location of creation / location where a group or organisation was formed / location where a group or organization was formed

Got 330 rows and 3 columns, showing the first 5 and last 5 rows below:
| type                                                            | typeLabel                                                  | count         |
| --------------------------------------------------------------- | ---------------------------------------------------------- | ------------- |
| single entity of population (wd:Q3055118)                       | single entity of population (lang:en)                      | 311 (xsd:int) |
| center for early childhood and primary education (wd:Q53566453) | center for early childhood and primary education (lang:en) | 218 (xsd:int) |
| hotel (wd:Q27686)                                               | hotel (lang:en)                                            | 197 (xsd:int) |
| main library (wd:Q12317349)                                     | main library (lang:en)                                     | 146 (xsd:int) |
| nucleus of singular population entity (wd:Q127386657)           | nucleus of singular population entity (lang:en)            | 133 (xsd:int) |
| ...                                                             | ...                                                        | ...           |
| faculty (wd:Q180958)                                            | faculty (lang:en)                                          | 1 (xsd:int)   |
| public enterprise (wd:Q17990971)                                | public enterprise (lang:en)                                | 1 (xsd:int)   |
| quintet (wd:Q389888)                                            | quintet (lang:en)                                          | 1 (xsd:int)   |
| ecomuseum (wd:Q1798450)                                         | ecomuseum (lang:en)                                        | 1 (xsd:int)   |
| university (wd:Q3918)                                           | university (lang:en)                                       | 1 (xsd:int)   |

Answer:
I executed a SPARQL query that finds items (?org) whose instance-of (?org wdt:P31 ?type) is a subtype of "organization" (wd:Q43229), and that are located in the Balearic Islands (wd:Q107356467) via common location properties (P131 transitive, P159, P276, P740). The query groups by ?type and returns the count of distinct organizations for each type, ordered by count descending.

Results summary:
- Total distinct organization types returned: 330

Top types by count (type — count):
1. single entity of population — 311
2. center for early childhood and primary education — 218
3. hotel — 197
4. main library — 146
5. nucleus of singular population entity — 133

The full SPARQL query is included above. If you want the complete list of all 330 types and counts (or the top N, or the results as CSV/JSON), tell me which format or N you prefer and I will retrieve/export them.

I executed a SPARQL query that finds items (?org) whose instance-of (?org wdt:P31 ?type) is a subtype of "organization" (wd:Q43229), and that are located in the Balearic Islands (wd:Q107356467) via common location properties (P131 transitive, P159, P276, P740). The query groups by ?type and returns the count of distinct organizations for each type, ordered by count descending.

Results summary:
- Total distinct organization types returned: 330

Top types by count (type — count):
1. single entity of population — 311
2. center for early childhood and primary education — 218
3. hotel — 197
4. main library — 146
5. nucleus of singular population entity — 133

The full SPARQL query is included above. If you want the complete list of all 330 types and counts (or the top N, or the results as CSV/JSON), tell me which format or N you prefer and I will retrieve/export them.

SPARQL query over wikidata:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
SELECT ?type ( SAMPLE( ?label ) AS ?typeLabel ) ( COUNT( DISTINCT ?org ) AS ?count ) WHERE {
  VALUES ?region {
    wd:Q107356467
  }
  ?org wdt:P31 ?type .
  {
    ?org wdt:P131 * ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131 * ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131 * ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131 * ?region .
  }
  ?type wdt:P279 * wd:Q43229 .
  OPTIONAL {
    ?type rdfs:label ?label .
    FILTER ( LANG( ?label ) = "en" )
  }
}
GROUP BY ?type
ORDER BY DESC ( ?count )

Using entities:
- Balearic Islands (wd:Q107356467): is instance of autonomous community of Spain / is instance of historical nationality / autonomous community of Spain
- organization (wd:Q43229), also known as institution, organisation, organisations, organization in sociology, organizations: is instance of social science concept / is subclass of person or organisation / is subclass of person or organization / is subclass of corporate body / is subclass of group of humans / is subclass of social system / is subclass of complex system / social entity established to meet needs or pursue goals / social entity with a collective goal / social entity with a collective goal / social entity with a collective goal

Using properties:
- located in the administrative territorial entity (wd:P131 as wdt), also known as administrative territorial entity, administrative territory, city, happens in, in, etc.: is subproperty of location / is subproperty of part of / the item is located on the territory of the following administrative entity / the item is located on the territory of the following administrative entity / the item is located on the territory of the following ... the item falls only partially into the administrative entity. / the item is located on the territory of the following ... the item falls only partially into the administrative entity.
- headquarters location (wd:P159 as wdt), also known as admin HQ, based in, garrison, head office location, head quarters, etc.: is subproperty of significant place / city or town where an organization's headquarters is or has been situated. Use P276 qualifier for specific building / specific location where an organisation's HQ is or has been located / specific location where an organisation's HQ is or has been located
- location (wd:P276 as wdt), also known as based in, city, from, held by, in, etc.: location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706. / location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706. / location of the object, structure or event. In the case of an ... use P706. Use P7153 for locations associated with the object
- subclass of (wd:P279 as wdt), also known as all members of this class also belong to, category of, form of, has superclass, is a class of, etc.: this item is a subclass (subset) of that item; ALL instances ... of volcanic landform); Everest is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain
- instance of (wd:P31 as wdt), also known as example of, has type, is a, is an, is of type, etc.: that class of which this subject is a particular example and ... a subclass of mountain (and an instance of volcanic landform) / type to which this subject corresponds/belongs. Different ... and the volcano is a type (instance) of volcanic landform
- location of formation (wd:P740 as wdt), also known as comes from, formation location, formation place, formed in, founded in, etc.: is subproperty of location of creation / location where a group or organisation was formed / location where a group or organization was formed

Execution result:
Got 330 rows and 3 columns, showing the first 5 and last 5 rows below:
| type                                                            | typeLabel                                                  | count         |
| --------------------------------------------------------------- | ---------------------------------------------------------- | ------------- |
| single entity of population (wd:Q3055118)                       | single entity of population (lang:en)                      | 311 (xsd:int) |
| center for early childhood and primary education (wd:Q53566453) | center for early childhood and primary education (lang:en) | 218 (xsd:int) |
| hotel (wd:Q27686)                                               | hotel (lang:en)                                            | 197 (xsd:int) |
| main library (wd:Q12317349)                                     | main library (lang:en)                                     | 146 (xsd:int) |
| nucleus of singular population entity (wd:Q127386657)           | nucleus of singular population entity (lang:en)            | 133 (xsd:int) |
| ...                                                             | ...                                                        | ...           |
| faculty (wd:Q180958)                                            | faculty (lang:en)                                          | 1 (xsd:int)   |
| public enterprise (wd:Q17990971)                                | public enterprise (lang:en)                                | 1 (xsd:int)   |
| quintet (wd:Q389888)                                            | quintet (lang:en)                                          | 1 (xsd:int)   |
| ecomuseum (wd:Q1798450)                                         | ecomuseum (lang:en)                                        | 1 (xsd:int)   |
| university (wd:Q3918)                                           | university (lang:en)                                       | 1 (xsd:int)   |

[System]
You are a question answering assistant. Your job is to generate a SPARQL query to answer a given user question.

You should follow a step-by-step approach to generate the SPARQL query:
1. Determine possible entities and properties implied by the user question.
2. Search for the entities and properties in the knowledge graphs. Where applicable, constrain the searches with already identified entities and properties.
3. Gradually build up the SPARQL query using the identified entities and properties. Start with simple queries and add more complexity as needed. Execute intermediate queries to get feedback and to verify your assumptions. You may need to refine or rethink your current plan based on the query results and go back to step 2 if needed, possibly multiple times.
4. Use the answer or cancel function to finalize your answer and stop the generation process.

Available knowledge graphs:
- wikidata at http://localhost:7001 with prefix index for entities and similarity index for properties, and notes:
  - P106 = occupation. Use wdt:P106 to get occupations and fetch English labels with rdfs:label + FILTER(LANG(?label)="en"). When returning human occupations confirm the subject is human (wdt:P31 wd:Q5) to avoid non-human items.
  - Population (P1082) and tabular (P4179): use wdt:P1082 for quick/direct values; for time-series/point-in-time use p:P1082 + ps:P1082 + pq:P585 and ORDER BY pq:P585 DESC. Inspect statement qualifiers (e.g., 'applies to part') and prov:wasDerivedFrom references (pr:P854 etc.) to detect city-proper vs metro/prefecture scopes before using values.
  - Common person properties: P31 (instance of human Q5), P106 (occupation), P569 (date of birth), P19 (place of birth), P27 (country of citizenship), P21 (sex/gender), P166 (award received). Use wdt: for direct values when possible.
  - P17 (country) can be incomplete/misleading for places (historical/overseas tags). To get modern cities in a country combine: instance-of city (P31=Q515) + wdt:P17 OR use wdt:P131* to find an admin parent whose wdt:P17 = the country. Also cross-check coordinates (P625) or admin hierarchy to spot outliers.
  - When filtering by date of birth (P569) use xsd:dateTime comparisons (e.g. >= "1900-01-01T00:00:00Z"^^xsd:dateTime). Be aware many items have year-only or imprecise dates and coverage is biased toward notable/public figures (sportspeople, politicians, artists).
  - To retrieve qualifiers (e.g., award year) use the statement/qualifier pattern: p:Pxxx / ps:Pxxx / pq:P585. Use wdt:Pxxx for normalized/direct values when you don't need qualifiers. Example: p:P166 + pq:P585 gives award year.
  - To get a person's occupations: use wdt:P106 for direct/normalized values and rdfs:label for human-readable names (FILTER(LANG(...))). Example: wd:Q... wdt:P106 ?occ . ?occ rdfs:label ?occLabel . FILTER(LANG(?occLabel)="en").
  - P166 = award received. Use wdt:P166 for normalized/direct values when you only need award items. To get award years or qualifiers use p:P166 / ps:P166 / pq:P585. Many statements lack pq:P585 — use OPTIONAL { ?stmt pq:P585 ?date } and ORDER BY DESC(?date). When listing award winners, filter ?person wdt:P31 wd:Q5 to ensure humans.
  - Population time-series pattern: wd:Q... p:P1082 ?stmt . ?stmt ps:P1082 ?pop . OPTIONAL { ?stmt pq:P585 ?date } . ORDER BY DESC(?date). pq:P585 is the point-in-time qualifier. IMPORTANT: time-series may mix scopes (city proper vs metro) — e.g., Tokyo has a 2016 entry ~38,140,000 likely metro vs smaller city figures. Inspect qualifiers/references for scope before use.
  - Use wdt:P131* to traverse the admin hierarchy and compare wdt:P17 on the place vs an admin parent to detect historical/colonial country assignments. When mismatches appear, inspect the admin parent's instance-of (P31), labels, qualifiers and references to interpret the historical scope.
  - wdt:P106 often yields multiple occupations for a person. Use GROUP_CONCAT(DISTINCT ?occLabel; separator=", ") or return multiple rows. Always fetch labels with rdfs:label + FILTER(LANG(?label)="en") to get readable occupation names.
  - When a search_entity returns multiple hits (person vs sculpture vs memorial), confirm you selected the human/statements by checking wdt:P31 (instance of) and relevant wdt: properties (e.g., wdt:P106). This avoids using a non-human QID by mistake.
  - search_autocomplete can be constrained with a SPARQL pattern containing ?search (e.g., SELECT * WHERE { ?search wdt:P31 wd:Q5 }). Use constraints to focus results (e.g., humans) and avoid ambiguous fallbacks; if it returns no results, fallback to search_entity and verify wdt:P31.
  - Use search_property_of_entity to find relevant properties for an entity (e.g., 'award' -> P166) and search_object_of_property to discover candidate objects (e.g., 'physicist' for P106). This reduces guessing P/Q ids and surfaces qualifiers.
  - Inspect statement references and qualifiers: use prov:wasDerivedFrom on p: statements to find sources, and check qualifiers (e.g., 'applies to part' or other scope qualifiers) to disambiguate city vs metro vs admin area. Reference labels can be empty; inspect reference node properties for URLs or publication dates.

Index types used for entities and properties:
- Prefix index: Retrieves items by overlap between query keywords and item words. The query keywords can match item words exactly or as prefixes.
- Similarity index: Retrieves items by cosine similarity between their embeddings and the query embedding.

General notes across knowledge graphs:
- Use rdfs:label + FILTER(LANG(?label)="en") for labels; avoid SERVICE wikibase:label. Use wdt:Pxxx for normalized/direct values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access statement qualifiers (e.g., award year via pq:P585). When dates matter, prefer xsd:dateTime and watch for year-only precision.
- Practical query patterns: use rdfs:label + FILTER(LANG(...)) for labels. Use wdt:Pxxx for direct/normalized values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access qualifiers (dates via pq:P585). For dates use xsd:dateTime and expect year-only precision. For places: combine P17 with P131 or coordinate (P625) filters to avoid historical/overseas mismatches.
- Use OPTIONAL for pq: qualifiers (e.g., pq:P585), sort by qualifier (ORDER BY pq:P585 DESC) to prefer recent values. Use GROUP_CONCAT to combine multiple labels/values in one row. Watch for typed literals (xsd:dateTime, xsd:decimal) when filtering or sorting.
- Before querying, use search_entity to resolve human-friendly names to wd:Q identifiers and verify instance-of (e.g., check wdt:P31 = wd:Q5 for humans) to avoid ambiguous matches. Prefer the top match but programmatically confirm P31 before using its data.
- Use search_property to confirm property identifiers (e.g., "country" -> P17) before embedding them in queries. This prevents mistakes from assuming an ID and helps pick the best property if multiple choices exist.
- search_autocomplete can fall back to an unconstrained search or error when there are too many candidates. If this happens (e.g., "more than the maximum supported number of subject candidates"), retry with narrower constraints such as instance-of (wdt:P31), additional type filters, or short prefixes to reduce the candidate set; otherwise fallback to search_entity and verify wdt:P31.
- Use list(...) to inspect all triples on an entity for exploration, but expect large results for notable items. Prefer wdt: properties or targeted p:/ps:/pq: patterns in SPARQL when you need normalized values or qualifiers, respectively.
- Before embedding property or item IDs in SPARQL, use search_property, search_property_of_entity, and search_object_of_property to discover the appropriate P/PID or object QIDs. This reduces errors from guessing IDs and surfaces better property alternatives and qualifiers.
- search_constrained and search_autocomplete can return no results for constrained queries or when the index is large. If they fail, fallback to search_entity + verify P31 (or use search_property_of_entity). Constrain with instance-of (wdt:P31) or other properties in the SPARQL to improve matches.
- When selecting awards by year, prefer xsd:dateTime range filters (e.g., >= "2001-01-01T00:00:00Z"^^xsd:dateTime && < "2002-01-01T00:00:00Z"^^xsd:dateTime) instead of YEAR() for portability and precision.
- When selecting award winners via wdt:P166, filter ?person wdt:P31 wd:Q5 to ensure humans — fictional characters or non-humans may have award claims. If you need award years use p:P166 / ps:P166 / pq:P585 and OPTIONAL { ?stmt pq:P585 ?year } to retrieve qualifier years.
- Use wdt:P625 (coordinates) together with wdt:P131* and wdt:P17 checks to validate a place's modern country or to filter by geography. When country labels mismatch historically, inspect admin parents and coordinates to resolve whether the item refers to historical/colonial scope or current boundaries.
- Prefer wdt:Pxxx for normalized/direct values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access qualifiers (e.g., pq:P585 for award year). Always fetch labels with rdfs:label + FILTER(LANG(?label) = "en").
- If search_autocomplete returns too many candidates or errors, retry with constraints (e.g., SELECT * WHERE { ?search wdt:P31 wd:Q5 }) or narrower query text. If still failing, fallback to search_entity and verify wdt:P31 for type checks.
- For award-year queries use p:P166 / ps:P166 / pq:P585 to access award statements and year qualifiers. Filter by xsd:dateTime ranges (e.g., >= "2020-01-01T00:00:00Z"^^xsd:dateTime && < "2021-01-01T00:00:00Z"^^xsd:dateTime) instead of YEAR() for robustness.
- Use search_property_of_entity to surface relevant properties for an entity (e.g., 'birth' -> P569/P19). list(...) can inspect triples but may return large results for notable items—prefer targeted wdt: patterns (wdt:Pxxx) or p:/ps:/pq: patterns when you need qualifiers.

SPARQL prefixes for use in function calls:
- bd: <http://www.bigdata.com/rdf#
- cc: <http://creativecommons.org/ns#
- data: <https://www.wikidata.org/wiki/Special:EntityData/
- dc: <http://purl.org/dc/elements/1.1/
- dct: <http://purl.org/dc/terms/
- foaf: <http://xmlns.com/foaf/0.1/
- geo: <http://www.opengis.net/ont/geosparql#
- geof: <http://www.opengis.net/def/function/geosparql/
- gn: <http://www.geonames.org/ontology#
- hint: <http://www.bigdata.com/queryHints#
- imdb: <https://www.imdb.com/
- math: <http://www.w3.org/2005/xpath-functions/math#
- ontolex: <http://www.w3.org/ns/lemon/ontolex#
- owl: <http://www.w3.org/2002/07/owl#
- p: <http://www.wikidata.org/prop/
- pq: <http://www.wikidata.org/prop/qualifier/
- pqn: <http://www.wikidata.org/prop/qualifier/value-normalized/
- pqv: <http://www.wikidata.org/prop/qualifier/value/
- pr: <http://www.wikidata.org/prop/reference/
- prn: <http://www.wikidata.org/prop/reference/value-normalized/
- prov: <http://www.w3.org/ns/prov#
- prv: <http://www.wikidata.org/prop/reference/value/
- ps: <http://www.wikidata.org/prop/statement/
- psn: <http://www.wikidata.org/prop/statement/value-normalized/
- psv: <http://www.wikidata.org/prop/statement/value/
- qb: <http://purl.org/linked-data/cube#
- qfn: <http://qlever.cs.uni-freiburg.de/function#
- ql: <http://qlever.cs.uni-freiburg.de/builtin-functions/
- qlss: <https://qlever.cs.uni-freiburg.de/spatialSearch/
- rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#
- rdfs: <http://www.w3.org/2000/01/rdf-schema#
- ref: <http://www.wikidata.org/reference/
- s: <http://www.wikidata.org/entity/statement/
- schema: <http://schema.org/
- skos: <http://www.w3.org/2004/02/skos/core#
- v: <http://www.wikidata.org/value/
- void: <http://rdfs.org/ns/void#
- wd: <http://www.wikidata.org/entity/
- wdno: <http://www.wikidata.org/prop/novalue/
- wdt: <http://www.wikidata.org/prop/direct/
- wdtn: <http://www.wikidata.org/prop/direct-normalized/
- wikibase: <http://wikiba.se/ontology#
- xsd: <http://www.w3.org/2001/XMLSchema#

Additional rules to follow:
- Explain your thought process before and after each step and function call.
- Do not just use or make up entity or property identifiers without verifying their existence in the knowledge graphs first.
- Do not ask the user for clarifications without first attempting to complete the task. If the task input is incomplete or ambiguous, try to make reasonable assumptions and document them.
- Do not use "SERVICE wikibase:label { bd:serviceParam wikibase:language ..." in SPARQL queries. It is not SPARQL standard and unsupported by the used QLever SPARQL endpoints. Use rdfs:label or similar properties to get labels instead.
- Always execute your final SPARQL query before giving an answer to make sure it returns the expected results.
- The SPARQL query should always return the actual identifiers / IRIs of the items in its result. It additionally may return labels or other human-readable information, but they are optional and should be put within optional clauses unless explicitly requested by the user.
- Do not stop early if there are still obvious improvements to be made to the SPARQL query. For example, keep refining your SPARQL query if its result contains irrelevant items or is missing items you expected.
- Do not perform additional computation (e.g. filtering, sorting, calculations) on the result of the SPARQL query to determine the answer. All computation should be done solely within SPARQL.
- For questions with a "True" or "False" answer the SPARQL query should be an ASK query.

[User] What are the types of organizations located in the Balearic Islands, along with the count of distinct organizations for each type, ordered by the count in descending order?

[Assistant]
Step 1: I'll find the Wikidata item for "Balearic Islands" so I can use it in the query. I'll search for the entity first. I'll explain my reasoning before and after the function call.

Question: Balearic Islands

Top 10 entity alternatives:
1. Balearic Islands (wd:Q5765), also known as Balearic Isles, Islas baleares: archipelago in the Mediterranean Sea / is instance of archipelago
2. Balearic Islands (wd:Q4850673): is instance of electoral district of the Spanish Congress / Spanish Congress Electoral District
3. Balearic Islands (wd:Q107356469): is instance of historical province of Spain / province
4. Balearic Islands (wd:Q107356467): is instance of autonomous community of Spain / is instance of historical nationality / autonomous community of Spain
5. Balearic Islands (wd:Q107356470): is instance of region of Spain / region (1833–1982)
6. Balearic Islands (wd:Q103891547): is instance of encyclopaedic article / is instance of encyclopedia article / encyclopedia article
7. flag of the Balearic Islands (wd:Q435103, matched via Balearic Islands flag), also known as Balearic Islands flag, the Balearic Islands flag: flag of the Spanish autonomous community of the Balearic Islands / is instance of flag of a country subdivision
8. history of Balearic Islands (wd:Q11925943, matched via Balearic Islands history), also known as Balearic Islands history: is instance of aspect of history
9. geography of the Balearic Islands (wd:Q11924065, matched via Balearic Islands geography), also known as Balearic Islands geography, the Balearic Islands geography: is instance of geography of geographic location
10. Balearic Islands Ombudsman (wd:Q11950661): is subclass of ombudsperson / is subclass of ombudsman / is subclass of Ombudsman / is instance of position

[Assistant]
I'll inspect the candidate item wd:Q107356467 (returned as an autonomous community) to confirm it's the official Wikidata item representing the Balearic Islands as an autonomous community. I'll list its triples (subject = that QID) to check instance-of (P31) and labels.

list

wd:Q107356467

Got 276 rows and 3 columns, showing the first 10 rows below:
| subject                          | property                                                    | object                                                                  |
| -------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------- |
| Balearic Islands (wd:Q107356467) | instance of (wdt:P31)                                       | autonomous community of Spain (wd:Q10742)                               |
| Balearic Islands (wd:Q107356467) | country (wdt:P17)                                           | Spain (wd:Q29)                                                          |
| Balearic Islands (wd:Q107356467) | located in the administrative territorial entity (wdt:P131) | Spain (wd:Q29)                                                          |
| Balearic Islands (wd:Q107356467) | coordinate location (wdt:P625)                              | POINT(3.000000 39.500000) (geo:wktLiteral)                              |
| Balearic Islands (wd:Q107356467) | Commons category (wdt:P373)                                 | Balearic Islands                                                        |
| Balearic Islands (wd:Q107356467) | image (wdt:P18)                                             | <http://commons.wikimedia.org/wiki/Special:FilePath/ConsolatdeMar2.jpg> |
| Balearic Islands (wd:Q107356467) | part of (wdt:P361)                                          | Catalan Countries (wd:Q234963)                                          |
| Balearic Islands (wd:Q107356467) | GeoNames ID (wdtn:P1566)                                    | <https://sws.geonames.org/2521383/>                                     |
| Balearic Islands (wd:Q107356467) | population (wdt:P1082)                                      | 1176659 (xsd:decimal)                                                   |
| Balearic Islands (wd:Q107356467) | inception (wdt:P571)                                        | 1229-01-01T00:00:00Z (xsd:dateTime)                                     |
| ...                              | ...                                                         | ...                                                                     |

[Assistant]
Now I'll search for properties commonly used to indicate where an organization is located (e.g., "headquarters location", "located in the administrative territorial entity", "location"). I'll inspect the property identifiers before using them.

Question: headquarters location

Top 10 property alternatives:
1. headquarters location (wd:P159 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn), also known as admin HQ, based in, garrison, head office location, head quarters, etc.: city or town where an organization's headquarters is or has been situated. Use P276 qualifier for specific building / specific location where an organisation's HQ is or has been located / specific location where an organisation's HQ is or has been located / is subproperty of significant place
2. capital (wd:P36 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via administrative headquarters), also known as administrative capital, administrative center, administrative centre, administrative headquarters, administrative seat, etc.: location (city, municipality) of governmental seat of the country, or administrative territorial entity / seat of government of a country, province, state or other type of administrative territorial entity / city of governmental seat of the country, state or administrative subdivision
3. occupant (wd:P466 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via location of), also known as home team, houses, inhabitant, lessee, location of, etc.: person or organization occupying a building or facility / person or organization occupying property / is subproperty of used by
4. operating area (wd:P2541 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via place of operation), also known as area of operations, area of responsibility, area operated, area served, areas served, etc.: geographic area or jurisdiction an organisation or industry operates in, serves, or has responsibility for / geographic area or jurisdiction an organisation or industry operates in, serves, or has responsibility for / geographic area or jurisdiction an organization or industry operates in, serves, or has responsibility for / is subproperty of location
5. work location (wd:P937 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via location of work), also known as active in, conducts business at, conducts business in, did work at, did work from, etc.: location where persons or organisations were actively participating in employment, business or other work / is subproperty of significant place / location where persons were active / is subproperty of location
6. location of creation (wd:P1071 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via manufacturing location), also known as assembly location, built at, built in, composed at, created at, etc.: place where the item was conceived or made; where applicable, location of final assembly / is subproperty of significant place
7. applies to jurisdiction (wd:P1001 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via of location), also known as applicable area, applicable country, applicable geographic place, applicable jurisdiction, applicable location, etc.: the item (institution, law, public office, public ... jurisdiction: a country, state, municipality, ...) / the item (an institution, law, public office ...) or ... jurisdiction: a country, state, municipality, ...) / is subproperty of characteristic of / is subproperty of significant place / is subproperty of operating area
8. location of formation (wd:P740 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via place of establishment), also known as comes from, formation location, formation place, formed in, founded in, etc.: location where a group or organisation was formed / location where a group or organization was formed / is subproperty of location of creation
9. coordinates of geographic center (wd:P5140 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via geographical center), also known as coordinates of geographic centre, geographical center, geographical centre, geographical midpoint, geographic center, etc.: coordinates of the center of an area. Use qualifier "determination method" (P459) to indicate how / coordinates of the centre of an area. Use qualifier "determination method" (P459) to indicate how / is subproperty of coordinate location
10. coordinate location (wd:P625 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via location), also known as co-ordinate location, co-ordinates, coordinates, co-ords, coords, etc.: geocoordinates of the subject. For Earth, please note that only WGS84 coordinating system is supported at the moment / coordinates of the subject / coordinates of the subject

[Assistant]
I'll find the property "located in the administrative territorial entity" (P131) to use for administrative location relationships.

Question: located in the administrative territorial entity

Top 10 property alternatives:
1. located in the administrative territorial entity (wd:P131 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn), also known as administrative territorial entity, administrative territory, city, happens in, in, etc.: the item is located on the territory of the following ... the item falls only partially into the administrative entity. / the item is located on the territory of the following ... the item falls only partially into the administrative entity. / the item is located on the territory of the following administrative entity / the item is located on the territory of the following administrative entity / is subproperty of location / is subproperty of part of
2. located in the present-day administrative territorial entity (wd:P3842 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via located in the current administrative territorial entity), also known as current administrative territorial entity, current location, currently in, located in present day administrative territorial entity, located in present-day administrative territorial entity, etc.: the item was located in the territory of this present-day ... unit; however the two did not at any point coexist in time / the item was located in the territory of this present-day ... unit; however the two did not at any point coexist in time / is subproperty of location / is subproperty of part of
3. located in the statistical territorial entity (wd:P8138 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn), also known as located in statistical territorial entity, statistical territorial entity, P8138: statistical territorial entity in which a place is located or ... is split into or part of several regions: add several values / is subproperty of location
4. territory overlaps (wd:P3179 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via partly located in territorial entity), also known as overlaps, partially coextensive with, partially coincident with, partially contains territorial extent, partially located in territorial entity, etc.: part or all of the area associated with (this) entity overlaps part or all of the area associated with that entity / part or all of the area associated with (this) entity overlaps part or all of the area associated with that entity / is subproperty of partially coincident with
5. contains the administrative territorial entity (wd:P150 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via contains administrative territorial entity), also known as contains, contains administrative territorial entity, divided into, divides into, has administrative divisions, etc.: (list of) direct subdivisions of an administrative territorial entity / (list of) direct subdivisions of an administrative division / (list of) direct subdivisions of an administrative division / is subproperty of has part(s) / is subproperty of has part
6. located in the religious territorial entity (wd:P5607 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via located in the ecclesiastical territorial entity), also known as Deanery, located in the ecclesiastical territorial entity, Parish, religious territorial entity, Vicariate, etc.: the item is located on the territory of the following ecclesiastical entity. Use P708 (diocese) for dioceses / the item is located on the territory of the following religious entity. Use P708 (diocese) for dioceses / is subproperty of location / is subproperty of part of
7. location (wd:P276 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via located in), also known as based in, city, from, held by, in, etc.: location of the object, structure or event. In the case of an ... use P706. Use P7153 for locations associated with the object / location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706. / location of the item, physical object or event is within. In ... use P131. In case of a distinct terrain feature use P706.
8. located in protected area (wd:P3018 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via located in territorial park), also known as located in bioreserve, located in biosphere reserve, located in conservation area, located in ecological protection area, located in national park, etc.: protected area where a place or geographical feature is physically located / is subproperty of located in the administrative territorial entity / the protected area a place or geographical feature belongs to
9. LAU (wd:P782 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via local administrative unit), also known as local administrative unit, P782: identifier for a local administrative unit, renamed from NUTS 4 and NUTS 5. Format: 2 letters followed by digits
10. associated electoral district (wd:P7938 as pr/psn/wdtn/ps/prn/p/pq/pqv/wdt/prv/psv/pqn, matched via located in the constituency), also known as associated constituency, constituency associated with place, electoral district associated with place, located in electoral district, located in the constituency, etc.: constituencies/electoral districts in which a place is ... from administrative entities (P131) in predefined countries

[Assistant]
I'll look up the Wikidata item for "organization" so I can restrict types to subclasses/instances of organizations. I will inspect search results and then verify the QID before using it.

Question: organization

Top 10 entity alternatives:
1. organization (wd:Q43229), also known as institution, organisation, organisations, organization in sociology, organizations: social entity established to meet needs or pursue goals / is instance of social science concept / is subclass of person or organisation / is subclass of person or organization / social entity with a collective goal / social entity with a collective goal / social entity with a collective goal / is subclass of group of humans / is subclass of corporate body / is subclass of complex system / is subclass of social system
2. .org (wd:Q32131, matched via .organization), also known as dot-org, .organization, .org domain: is instance of generic top-level domain / generic top-level domain
3. The Organization (wd:Q1986084, matched via Organization), also known as Organization: 1971 film by Don Medford / is instance of film
4. Organization (wd:Q105755428): Turkish intelligence series broadcast on TRT 1 / is instance of television series / is instance of serial
5. Samaritans (wd:Q2256668, matched via Organization), also known as Organization: Swiss first aid organization / is instance of organization / is instance of organisation / is instance of aid agency
6. organization (wd:Q4827314), also known as auxiliary organization: secondary body of the Church of Jesus Christ of Latter-day Saints / is subclass of Christian organization
7. Organization (wd:Q7101933): is instance of scientific journal / peer-reviewed academic journal
8. Organization (wd:Q33771005): is instance of written work / essay by Parke Godwin
9. organization (wd:Q2204053): is subclass of government / Dutch form of government
10. organization (wd:Q2029841), also known as organisation, organizing, to organize: concept in economics: activity in which something is accomplished / is instance of concept / is subclass of agent

[Assistant]
I'll run a SPARQL query that:
- finds items (?org) that are instances (P31) of some type (?type);
- selects organizations that are located in the Balearic Islands via common location properties: P131 (located in administrative territorial entity, transitive), P159 (headquarters location), P276 (location) and P740 (location of formation) — each checked so the location or its admin parent chain leads to the Balearic Islands (wd:Q107356467);
- restricts ?type to be a subclass (P279*) of "organization" (wd:Q43229) so we return organization types only;
- groups counts of distinct organizations per ?type and orders by descending count.

Now I'll execute the query to get the counts.

execute

SELECT ?type (SAMPLE(?typeLabel) AS ?typeLabel) (COUNT(DISTINCT ?org) AS ?count) WHERE {
  VALUES ?region { wd:Q107356467 }

  ?org wdt:P31 ?type .

  {
    ?org wdt:P131* ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131* ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131* ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131* ?region .
  }

  ?type wdt:P279* wd:Q43229 .
  OPTIONAL { ?type rdfs:label ?typeLabel . FILTER(LANG(?typeLabel) = "en") }
}
GROUP BY ?type ?typeLabel
ORDER BY DESC(?count)

SPARQL execution failed:
Invalid SPARQL query: The target ?typeLabel of an AS clause was already used in the query body.

[Assistant]
I'll fix the label variable collision by using ?label in the OPTIONAL and alias SAMPLE(?label) AS ?typeLabel, then re-run the query.

SELECT ?type (SAMPLE(?label) AS ?typeLabel) (COUNT(DISTINCT ?org) AS ?count) WHERE {
  VALUES ?region { wd:Q107356467 }

  ?org wdt:P31 ?type .

  {
    ?org wdt:P131* ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131* ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131* ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131* ?region .
  }

  ?type wdt:P279* wd:Q43229 .
  OPTIONAL { ?type rdfs:label ?label . FILTER(LANG(?label) = "en") }
}
GROUP BY ?type
ORDER BY DESC(?count)

SPARQL execution failed:
HTTPConnectionPool(host='localhost', port=7001): Read timed out. (read timeout=30)

[Assistant]
The endpoint timed out on that attempt; I'll retry the same query once more.

SELECT ?type (SAMPLE(?label) AS ?typeLabel) (COUNT(DISTINCT ?org) AS ?count) WHERE {
  VALUES ?region { wd:Q107356467 }

  ?org wdt:P31 ?type .

  {
    ?org wdt:P131* ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131* ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131* ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131* ?region .
  }

  ?type wdt:P279* wd:Q43229 .
  OPTIONAL { ?type rdfs:label ?label . FILTER(LANG(?label) = "en") }
}
GROUP BY ?type
ORDER BY DESC(?count)

Got 330 rows and 3 columns, showing the first 5 and last 5 rows below:
| type                                                            | typeLabel                                                  | count         |
| --------------------------------------------------------------- | ---------------------------------------------------------- | ------------- |
| single entity of population (wd:Q3055118)                       | single entity of population (lang:en)                      | 311 (xsd:int) |
| center for early childhood and primary education (wd:Q53566453) | center for early childhood and primary education (lang:en) | 218 (xsd:int) |
| hotel (wd:Q27686)                                               | hotel (lang:en)                                            | 197 (xsd:int) |
| main library (wd:Q12317349)                                     | main library (lang:en)                                     | 146 (xsd:int) |
| nucleus of singular population entity (wd:Q127386657)           | nucleus of singular population entity (lang:en)            | 133 (xsd:int) |
| ...                                                             | ...                                                        | ...           |
| faculty (wd:Q180958)                                            | faculty (lang:en)                                          | 1 (xsd:int)   |
| public enterprise (wd:Q17990971)                                | public enterprise (lang:en)                                | 1 (xsd:int)   |
| quintet (wd:Q389888)                                            | quintet (lang:en)                                          | 1 (xsd:int)   |
| ecomuseum (wd:Q1798450)                                         | ecomuseum (lang:en)                                        | 1 (xsd:int)   |
| university (wd:Q3918)                                           | university (lang:en)                                       | 1 (xsd:int)   |

[Assistant]
I'll run a follow-up query limited to the top 20 rows so I can list them explicitly in the final answer.

SELECT ?type ?typeLabel (COUNT(DISTINCT ?org) AS ?count) WHERE {
  VALUES ?region { wd:Q107356467 }

  ?org wdt:P31 ?type .

  {
    ?org wdt:P131* ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131* ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131* ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131* ?region .
  }

  ?type wdt:P279* wd:Q43229 .
  OPTIONAL { ?type rdfs:label ?typeLabel . FILTER(LANG(?typeLabel) = "en") }
}
GROUP BY ?type ?typeLabel
ORDER BY DESC(?count)
LIMIT 20

SPARQL execution failed:
HTTPConnectionPool(host='localhost', port=7001): Read timed out. (read timeout=30)

[Assistant]
answer

SELECT ?type (SAMPLE(?label) AS ?typeLabel) (COUNT(DISTINCT ?org) AS ?count) WHERE {
  VALUES ?region { wd:Q107356467 }

  ?org wdt:P31 ?type .

  {
    ?org wdt:P131* ?region .
  } UNION {
    ?org wdt:P159 ?place .
    ?place wdt:P131* ?region .
  } UNION {
    ?org wdt:P276 ?place2 .
    ?place2 wdt:P131* ?region .
  } UNION {
    ?org wdt:P740 ?place3 .
    ?place3 wdt:P131* ?region .
  }

  ?type wdt:P279* wd:Q43229 .
  OPTIONAL { ?type rdfs:label ?label . FILTER(LANG(?label) = "en") }
}
GROUP BY ?type
ORDER BY DESC(?count)

Answer:
I executed a SPARQL query that finds items (?org) whose instance-of (?org wdt:P31 ?type) is a subtype of "organization" (wd:Q43229), and that are located in the Balearic Islands (wd:Q107356467) via common location properties (P131 transitive, P159, P276, P740). The query groups by ?type and returns the count of distinct organizations for each type, ordered by count descending.

Results summary:
- Total distinct organization types returned: 330

Top types by count (type — count):
1. single entity of population — 311
2. center for early childhood and primary education — 218
3. hotel — 197
4. main library — 146
5. nucleus of singular population entity — 133

The full SPARQL query is included above. If you want the complete list of all 330 types and counts (or the top N, or the results as CSV/JSON), tell me which format or N you prefer and I will retrieve/export them.


PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
SELECT DISTINCT ?item ?itemLabel WHERE {
  ?item wdt:P279 * wd:Q87167 .
  OPTIONAL {
    ?item rdfs:label ?itemLabel .
    FILTER ( LANG( ?itemLabel ) = "en" )
  }
}
ORDER BY ?itemLabel

Using entities:
- manuscript (wd:Q87167), also known as manuscript book, manuscripts, MS, MSS: is instance of document genre / is subclass of two-dimensional visual artwork / is subclass of item of collection or exhibition / is subclass of document / document written by hand

Using properties:
- subclass of (wd:P279 as wdt), also known as all members of this class also belong to, category of, form of, has superclass, is a class of, etc.: this item is a subclass (subset) of that item; ALL instances ... of volcanic landform); Everest is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain

Answer: I identified the manuscript item as wd:Q87167 and ran a transitive subclass query. The query returns 195 distinct items that are subclasses (at any level) of manuscript. Many results include their English labels; some items have no English label available. The SPARQL query above is the final query used to produce the list.

I identified the manuscript item as wd:Q87167 and ran a transitive subclass query. The query returns 195 distinct items that are subclasses (at any level) of manuscript. Many results include their English labels; some items have no English label available. The SPARQL query above is the final query used to produce the list.

SPARQL query over wikidata:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
SELECT DISTINCT ?item ?itemLabel WHERE {
  ?item wdt:P279 * wd:Q87167 .
  OPTIONAL {
    ?item rdfs:label ?itemLabel .
    FILTER ( LANG( ?itemLabel ) = "en" )
  }
}
ORDER BY ?itemLabel

Using entities:
- manuscript (wd:Q87167), also known as manuscript book, manuscripts, MS, MSS: is instance of document genre / is subclass of two-dimensional visual artwork / is subclass of item of collection or exhibition / is subclass of document / document written by hand

Using properties:
- subclass of (wd:P279 as wdt), also known as all members of this class also belong to, category of, form of, has superclass, is a class of, etc.: this item is a subclass (subset) of that item; ALL instances ... of volcanic landform); Everest is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain / this item is a subclass (subset) of that item; all instances ... instance of volcanic landform); K2 is an instance of mountain

Execution result:
Got 195 rows and 2 columns, showing the first 5 and last 5 rows below:
| item                           | itemLabel                  |
| ------------------------------ | -------------------------- |
| wd:Q11362982                   |                            |
| wd:Q21089188                   |                            |
| wd:Q13430250                   |                            |
| wd:Q2135500                    |                            |
| wd:Q11071212                   |                            |
| ...                            | ...                        |
| Usadha (wd:Q104086307)         | Usadha (lang:en)           |
| Volkshandschrift (wd:Q2531964) | Volkshandschrift (lang:en) |
| Wariga (wd:Q104080231)         | Wariga (lang:en)           |
| Weda (wd:Q104080336)           | Weda (lang:en)             |
| yōkai emaki (wd:Q11446810)     | yōkai emaki (lang:en)      |

[System]
You are a question answering assistant. Your job is to generate a SPARQL query to answer a given user question.

You should follow a step-by-step approach to generate the SPARQL query:
1. Determine possible entities and properties implied by the user question.
2. Search for the entities and properties in the knowledge graphs. Where applicable, constrain the searches with already identified entities and properties.
3. Gradually build up the SPARQL query using the identified entities and properties. Start with simple queries and add more complexity as needed. Execute intermediate queries to get feedback and to verify your assumptions. You may need to refine or rethink your current plan based on the query results and go back to step 2 if needed, possibly multiple times.
4. Use the answer or cancel function to finalize your answer and stop the generation process.

Available knowledge graphs:
- wikidata at http://localhost:7001 with prefix index for entities and similarity index for properties, and notes:
  - P106 = occupation. Use wdt:P106 to get occupations and fetch English labels with rdfs:label + FILTER(LANG(?label)="en"). When returning human occupations confirm the subject is human (wdt:P31 wd:Q5) to avoid non-human items.
  - Population (P1082) and tabular (P4179): use wdt:P1082 for quick/direct values; for time-series/point-in-time use p:P1082 + ps:P1082 + pq:P585 and ORDER BY pq:P585 DESC. Inspect statement qualifiers (e.g., 'applies to part') and prov:wasDerivedFrom references (pr:P854 etc.) to detect city-proper vs metro/prefecture scopes before using values.
  - Common person properties: P31 (instance of human Q5), P106 (occupation), P569 (date of birth), P19 (place of birth), P27 (country of citizenship), P21 (sex/gender), P166 (award received). Use wdt: for direct values when possible.
  - P17 (country) can be incomplete/misleading for places (historical/overseas tags). To get modern cities in a country combine: instance-of city (P31=Q515) + wdt:P17 OR use wdt:P131* to find an admin parent whose wdt:P17 = the country. Also cross-check coordinates (P625) or admin hierarchy to spot outliers.
  - When filtering by date of birth (P569) use xsd:dateTime comparisons (e.g. >= "1900-01-01T00:00:00Z"^^xsd:dateTime). Be aware many items have year-only or imprecise dates and coverage is biased toward notable/public figures (sportspeople, politicians, artists).
  - To retrieve qualifiers (e.g., award year) use the statement/qualifier pattern: p:Pxxx / ps:Pxxx / pq:P585. Use wdt:Pxxx for normalized/direct values when you don't need qualifiers. Example: p:P166 + pq:P585 gives award year.
  - To get a person's occupations: use wdt:P106 for direct/normalized values and rdfs:label for human-readable names (FILTER(LANG(...))). Example: wd:Q... wdt:P106 ?occ . ?occ rdfs:label ?occLabel . FILTER(LANG(?occLabel)="en").
  - P166 = award received. Use wdt:P166 for normalized/direct values when you only need award items. To get award years or qualifiers use p:P166 / ps:P166 / pq:P585. Many statements lack pq:P585 — use OPTIONAL { ?stmt pq:P585 ?date } and ORDER BY DESC(?date). When listing award winners, filter ?person wdt:P31 wd:Q5 to ensure humans.
  - Population time-series pattern: wd:Q... p:P1082 ?stmt . ?stmt ps:P1082 ?pop . OPTIONAL { ?stmt pq:P585 ?date } . ORDER BY DESC(?date). pq:P585 is the point-in-time qualifier. IMPORTANT: time-series may mix scopes (city proper vs metro) — e.g., Tokyo has a 2016 entry ~38,140,000 likely metro vs smaller city figures. Inspect qualifiers/references for scope before use.
  - Use wdt:P131* to traverse the admin hierarchy and compare wdt:P17 on the place vs an admin parent to detect historical/colonial country assignments. When mismatches appear, inspect the admin parent's instance-of (P31), labels, qualifiers and references to interpret the historical scope.
  - wdt:P106 often yields multiple occupations for a person. Use GROUP_CONCAT(DISTINCT ?occLabel; separator=", ") or return multiple rows. Always fetch labels with rdfs:label + FILTER(LANG(?label)="en") to get readable occupation names.
  - When a search_entity returns multiple hits (person vs sculpture vs memorial), confirm you selected the human/statements by checking wdt:P31 (instance of) and relevant wdt: properties (e.g., wdt:P106). This avoids using a non-human QID by mistake.
  - search_autocomplete can be constrained with a SPARQL pattern containing ?search (e.g., SELECT * WHERE { ?search wdt:P31 wd:Q5 }). Use constraints to focus results (e.g., humans) and avoid ambiguous fallbacks; if it returns no results, fallback to search_entity and verify wdt:P31.
  - Use search_property_of_entity to find relevant properties for an entity (e.g., 'award' -> P166) and search_object_of_property to discover candidate objects (e.g., 'physicist' for P106). This reduces guessing P/Q ids and surfaces qualifiers.
  - Inspect statement references and qualifiers: use prov:wasDerivedFrom on p: statements to find sources, and check qualifiers (e.g., 'applies to part' or other scope qualifiers) to disambiguate city vs metro vs admin area. Reference labels can be empty; inspect reference node properties for URLs or publication dates.

Index types used for entities and properties:
- Prefix index: Retrieves items by overlap between query keywords and item words. The query keywords can match item words exactly or as prefixes.
- Similarity index: Retrieves items by cosine similarity between their embeddings and the query embedding.

General notes across knowledge graphs:
- Use rdfs:label + FILTER(LANG(?label)="en") for labels; avoid SERVICE wikibase:label. Use wdt:Pxxx for normalized/direct values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access statement qualifiers (e.g., award year via pq:P585). When dates matter, prefer xsd:dateTime and watch for year-only precision.
- Practical query patterns: use rdfs:label + FILTER(LANG(...)) for labels. Use wdt:Pxxx for direct/normalized values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access qualifiers (dates via pq:P585). For dates use xsd:dateTime and expect year-only precision. For places: combine P17 with P131 or coordinate (P625) filters to avoid historical/overseas mismatches.
- Use OPTIONAL for pq: qualifiers (e.g., pq:P585), sort by qualifier (ORDER BY pq:P585 DESC) to prefer recent values. Use GROUP_CONCAT to combine multiple labels/values in one row. Watch for typed literals (xsd:dateTime, xsd:decimal) when filtering or sorting.
- Before querying, use search_entity to resolve human-friendly names to wd:Q identifiers and verify instance-of (e.g., check wdt:P31 = wd:Q5 for humans) to avoid ambiguous matches. Prefer the top match but programmatically confirm P31 before using its data.
- Use search_property to confirm property identifiers (e.g., "country" -> P17) before embedding them in queries. This prevents mistakes from assuming an ID and helps pick the best property if multiple choices exist.
- search_autocomplete can fall back to an unconstrained search or error when there are too many candidates. If this happens (e.g., "more than the maximum supported number of subject candidates"), retry with narrower constraints such as instance-of (wdt:P31), additional type filters, or short prefixes to reduce the candidate set; otherwise fallback to search_entity and verify wdt:P31.
- Use list(...) to inspect all triples on an entity for exploration, but expect large results for notable items. Prefer wdt: properties or targeted p:/ps:/pq: patterns in SPARQL when you need normalized values or qualifiers, respectively.
- Before embedding property or item IDs in SPARQL, use search_property, search_property_of_entity, and search_object_of_property to discover the appropriate P/PID or object QIDs. This reduces errors from guessing IDs and surfaces better property alternatives and qualifiers.
- search_constrained and search_autocomplete can return no results for constrained queries or when the index is large. If they fail, fallback to search_entity + verify P31 (or use search_property_of_entity). Constrain with instance-of (wdt:P31) or other properties in the SPARQL to improve matches.
- When selecting awards by year, prefer xsd:dateTime range filters (e.g., >= "2001-01-01T00:00:00Z"^^xsd:dateTime && < "2002-01-01T00:00:00Z"^^xsd:dateTime) instead of YEAR() for portability and precision.
- When selecting award winners via wdt:P166, filter ?person wdt:P31 wd:Q5 to ensure humans — fictional characters or non-humans may have award claims. If you need award years use p:P166 / ps:P166 / pq:P585 and OPTIONAL { ?stmt pq:P585 ?year } to retrieve qualifier years.
- Use wdt:P625 (coordinates) together with wdt:P131* and wdt:P17 checks to validate a place's modern country or to filter by geography. When country labels mismatch historically, inspect admin parents and coordinates to resolve whether the item refers to historical/colonial scope or current boundaries.
- Prefer wdt:Pxxx for normalized/direct values when qualifiers aren't needed. Use p:Pxxx / ps:Pxxx / pq:Pxxx to access qualifiers (e.g., pq:P585 for award year). Always fetch labels with rdfs:label + FILTER(LANG(?label) = "en").
- If search_autocomplete returns too many candidates or errors, retry with constraints (e.g., SELECT * WHERE { ?search wdt:P31 wd:Q5 }) or narrower query text. If still failing, fallback to search_entity and verify wdt:P31 for type checks.
- For award-year queries use p:P166 / ps:P166 / pq:P585 to access award statements and year qualifiers. Filter by xsd:dateTime ranges (e.g., >= "2020-01-01T00:00:00Z"^^xsd:dateTime && < "2021-01-01T00:00:00Z"^^xsd:dateTime) instead of YEAR() for robustness.
- Use search_property_of_entity to surface relevant properties for an entity (e.g., 'birth' -> P569/P19). list(...) can inspect triples but may return large results for notable items—prefer targeted wdt: patterns (wdt:Pxxx) or p:/ps:/pq: patterns when you need qualifiers.

SPARQL prefixes for use in function calls:
- bd: <http://www.bigdata.com/rdf#
- cc: <http://creativecommons.org/ns#
- data: <https://www.wikidata.org/wiki/Special:EntityData/
- dc: <http://purl.org/dc/elements/1.1/
- dct: <http://purl.org/dc/terms/
- foaf: <http://xmlns.com/foaf/0.1/
- geo: <http://www.opengis.net/ont/geosparql#
- geof: <http://www.opengis.net/def/function/geosparql/
- gn: <http://www.geonames.org/ontology#
- hint: <http://www.bigdata.com/queryHints#
- imdb: <https://www.imdb.com/
- math: <http://www.w3.org/2005/xpath-functions/math#
- ontolex: <http://www.w3.org/ns/lemon/ontolex#
- owl: <http://www.w3.org/2002/07/owl#
- p: <http://www.wikidata.org/prop/
- pq: <http://www.wikidata.org/prop/qualifier/
- pqn: <http://www.wikidata.org/prop/qualifier/value-normalized/
- pqv: <http://www.wikidata.org/prop/qualifier/value/
- pr: <http://www.wikidata.org/prop/reference/
- prn: <http://www.wikidata.org/prop/reference/value-normalized/
- prov: <http://www.w3.org/ns/prov#
- prv: <http://www.wikidata.org/prop/reference/value/
- ps: <http://www.wikidata.org/prop/statement/
- psn: <http://www.wikidata.org/prop/statement/value-normalized/
- psv: <http://www.wikidata.org/prop/statement/value/
- qb: <http://purl.org/linked-data/cube#
- qfn: <http://qlever.cs.uni-freiburg.de/function#
- ql: <http://qlever.cs.uni-freiburg.de/builtin-functions/
- qlss: <https://qlever.cs.uni-freiburg.de/spatialSearch/
- rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#
- rdfs: <http://www.w3.org/2000/01/rdf-schema#
- ref: <http://www.wikidata.org/reference/
- s: <http://www.wikidata.org/entity/statement/
- schema: <http://schema.org/
- skos: <http://www.w3.org/2004/02/skos/core#
- v: <http://www.wikidata.org/value/
- void: <http://rdfs.org/ns/void#
- wd: <http://www.wikidata.org/entity/
- wdno: <http://www.wikidata.org/prop/novalue/
- wdt: <http://www.wikidata.org/prop/direct/
- wdtn: <http://www.wikidata.org/prop/direct-normalized/
- wikibase: <http://wikiba.se/ontology#
- xsd: <http://www.w3.org/2001/XMLSchema#

Additional rules to follow:
- Explain your thought process before and after each step and function call.
- Do not just use or make up entity or property identifiers without verifying their existence in the knowledge graphs first.
- Do not ask the user for clarifications without first attempting to complete the task. If the task input is incomplete or ambiguous, try to make reasonable assumptions and document them.
- Do not use "SERVICE wikibase:label { bd:serviceParam wikibase:language ..." in SPARQL queries. It is not SPARQL standard and unsupported by the used QLever SPARQL endpoints. Use rdfs:label or similar properties to get labels instead.
- Always execute your final SPARQL query before giving an answer to make sure it returns the expected results.
- The SPARQL query should always return the actual identifiers / IRIs of the items in its result. It additionally may return labels or other human-readable information, but they are optional and should be put within optional clauses unless explicitly requested by the user.
- Do not stop early if there are still obvious improvements to be made to the SPARQL query. For example, keep refining your SPARQL query if its result contains irrelevant items or is missing items you expected.
- Do not perform additional computation (e.g. filtering, sorting, calculations) on the result of the SPARQL query to determine the answer. All computation should be done solely within SPARQL.
- For questions with a "True" or "False" answer the SPARQL query should be an ASK query.

[User] Which distinct items are subclasses, at any level, of a manuscript (a document written by hand)?

[Assistant]
Step 1 — plan:
- Find the Wikidata item for "manuscript (a document written by hand)" using a search.
- Then find all items that are subclasses (wdt:P279) of that item at any depth (transitive P279*).
- Return the distinct item IRIs (and optionally English labels) as the query result.
I'll first search for the manuscript item.

Question: manuscript

Top 10 entity alternatives:
1. manuscript (wd:Q87167), also known as manuscript book, manuscripts, MS, MSS: is subclass of item of collection or exhibition / is subclass of two-dimensional visual artwork / is instance of document genre / document written by hand / is subclass of document
2. block lettering (wd:Q1261015, matched via manuscript), also known as ball and stick, block letter, block letters, manuscript, printscript, etc.: sans-serif (or "gothic") style of writing in many scripts in ... print"; may also be used as a synonym of block capitals / is subclass of handwriting style / is subclass of disjoined hand
3. manuscript (wd:Q2376293), also known as manuscript format, manuscript (publishing): work that an author submits to a publisher or editor for publication / is subclass of literary work
4. Genkou (wd:Q127698834, matched via manuscript), also known as manuscript: Writings and other works intended for publication or presentation.
5. Manuscript (wd:Q16411389): is instance of album / album
6. Manuscript (wd:Q60851530): studio album by Manizha / is instance of album
7. Manuscript (wd:Q122933956): sculpture by Seymour Lipton / is instance of sculpture
8. Manuscript (wd:Q125094390): decorative artwork (glass) by Robert Kehlmann / is instance of decorative art / is instance of glass
9. manuscripts (wd:Q131469763, matched via manuscript), also known as manuscript, manuscripts as topic: is subclass of communication medium / is subclass of medium / study of manuscripts
10. Manuscript (wd:Q103955283): is instance of encyclopaedic article / is instance of encyclopedia article / encyclopedia article

[Assistant]
I'll run a SPARQL query to retrieve all distinct items that are (transitive) subclasses of the manuscript item wd:Q87167, and fetch their English labels for readability. I'll order by label. Now executing the query to verify results.

execute

PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?item ?itemLabel WHERE {
  ?item wdt:P279* wd:Q87167 .
  OPTIONAL { ?item rdfs:label ?itemLabel . FILTER(LANG(?itemLabel) = "en") }
}
ORDER BY ?itemLabel

[Assistant]
After discovering the correct manuscript item (wd:Q87167) and executing a verification query, I obtained 195 distinct subclasses (some lack English labels). Below I return the final SPARQL query I ran and a short summary of the results.

answer

PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?item ?itemLabel WHERE {
  ?item wdt:P279* wd:Q87167 .
  OPTIONAL { ?item rdfs:label ?itemLabel . FILTER(LANG(?itemLabel) = "en") }
}
ORDER BY ?itemLabel

Answer: I identified the manuscript item as wd:Q87167 and ran a transitive subclass query. The query returns 195 distinct items that are subclasses (at any level) of manuscript. Many results include their English labels; some items have no English label available. The SPARQL query above is the final query used to produce the list.